programing tip

Ruby on Rails에서 DateTime을 간단한 날짜로 변환

itbloger 2020. 8. 5. 07:55
반응형

Ruby on Rails에서 DateTime을 간단한 날짜로 변환


db에 datetime 열이 있는데 사용자에게 표시 할 때 간단한 날짜로 변환하고 싶습니다.

어떻게해야합니까?

데프 shown_date
  # to_date는 존재하지 않지만 내가 찾고있는 것입니다.
  self.date || self.exif_date_time_original.to_date
종료

DateTime#to_date ActiveSupport에는 존재합니다 :

$ irb
>> DateTime.new.to_date
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
    from (irb):1

>> require 'active_support/core_ext'
=> true

>> DateTime.new.to_date
=> Mon, 01 Jan -4712

안녕하세요 collimarco :) 루비 strftime 방법을 사용하여 자신의 날짜 / 시간 표시를 만들 수 있습니다 .

time.strftime (string) => 문자열

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character

   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"

Ruby 1.9.2 이상에서는 DateTime에 .to_date 함수를 추가했습니다.

http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date

이 인스턴스 메소드는 1.8.7과 같은 이전 버전에는 존재하지 않는 것 같습니다.


오래된 루비 (1.8.x) :

myDate = Date.parse(myDateTime.to_s)

나는 최근 에이 과정을 단순화하고 당신의 견해 등을 정리하기 위해 보석을 썼습니다.

Check it out at: http://github.com/platform45/easy_dates


Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.

self.date || self.exif_date_time_original.to_s

참고URL : https://stackoverflow.com/questions/1110411/transform-datetime-into-simple-date-in-ruby-on-rails

반응형