Ruby on Rails를 사용하여 날짜 형식 지정
flickr api는 게시 된 날짜를 유닉스 타임 스탬프 1로 제공합니다. " The posted date is always passed around as a unix timestamp, which is an unsigned integer specifying the number of seconds since Jan 1st 1970 GMT.
"
예를 들어, 다음은 날짜 ' 1100897479
'입니다. Ruby on Rails를 사용하여 어떻게 포맷합니까?
타임 스탬프 문자열을 구문 분석하고 시간 객체를 가지면 (자세한 내용은 다른 답변 참조) Rails의 Time.to_formatted_s 를 사용할 수 있습니다 . 기호로 지정할 수있는 여러 형식이 내장되어 있습니다.
인용문:
time = Time.now # => Thu Jan 18 06:10:17 CST 2007
time.to_formatted_s(:time) # => "06:10"
time.to_s(:time) # => "06:10"
time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
time.to_formatted_s(:number) # => "20070118061017"
time.to_formatted_s(:short) # => "18 Jan 06:10"
time.to_formatted_s(:long) # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
(Time.to_s는 별칭입니다)
일반적으로 이니셜 라이저에서 자신 만의 형식을 정의 할 수도 있습니다 ( 이를 지적한 Dave Newton 에게 감사드립니다 ). 이것이 수행되는 방법입니다.
# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = "%B %Y"
Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
여기에 대답 할 방법이 있습니다.
따라서 먼저 타임 스탬프를 실제 Ruby 날짜 / 시간으로 변환해야합니다. 페이스 북에서 문자열이나 정수로받은 경우 다음과 같이해야합니다.
my_date = Time.at(timestamp_from_facebook.to_i)
좋습니다. 이제 이미 날짜 개체가 있다고 가정합니다.
to_formatted_s 는 날짜를 형식화 된 문자열로 바꾸는 편리한 Ruby 함수입니다.
다음은 사용 예입니다.
time = Time.now # => Thu Jan 18 06:10:17 CST 2007
time.to_formatted_s(:time) # => "06:10"
time.to_s(:time) # => "06:10"
time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
time.to_formatted_s(:number) # => "20070118061017"
time.to_formatted_s(:short) # => "18 Jan 06:10"
time.to_formatted_s(:long) # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
보시다시피 : db, : number, : short ...는 사용자 지정 날짜 형식입니다.
사용자 지정 형식을 추가하려면 config / initializers / time_formats.rb 파일을 만들고 여기에 고유 한 형식을 추가하면됩니다. 예를 들면 다음과 같습니다.
Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015
여기서 : month_day_comma_year 는 형식 이름 (원하는대로 변경할 수 있음)이며, 여기서 % B % e, % Y 는 유닉스 날짜 형식입니다.
다음은 유닉스 날짜 구문에 대한 간단한 치트 시트이므로 사용자 지정 형식을 빠르게 설정할 수 있습니다.
From http://linux.die.net/man/3/strftime
%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)
%e - Day of the month without leading 0 (1..31)
%g - Year in YY (00-99)
%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"
이것이 당신을 도왔기를 바랍니다. 나는 또한 누군가가 선호하는 경우를 대비 하여이 작은 가이드 의 github 요점 을 만들었습니다 .
strftime
(문서) 를 사용하는 것이 가장 쉽습니다 .
보기 쪽에서 사용하는 경우 도우미로 감싸는 것이 좋습니다.
@CMW의 대답은 돈에 대한 것입니다. 이 답변을 이니셜 라이저를 구성하여 Date 및 Time 개체가 모두 서식을 갖도록 구성하는 방법에 대한 예제로 추가했습니다.
config / initializers / time_formats.rb
date_formats = {
concise: '%d-%b-%Y' # 13-Jan-2014
}
Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats
또한 다음 두 명령은 DATE_FORMATS
현재 환경의 모든 항목을 반복 하고 각 형식으로 오늘 날짜와 시간을 표시합니다.
Date::DATE_FORMATS.keys.each{|k| puts [k,Date.today.to_s(k)].join(':- ')}
Time::DATE_FORMATS.keys.each{|k| puts [k,Time.now.to_s(k)].join(':- ')}
에서보세요 localize
, 또는l
예 :
l Time.at(1100897479)
First you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:
my_date = Time.at(timestamp_from_facebook.to_i)
Then to format it nicely in the view, you can just use to_s
(for the default formatting):
<%= my_date.to_s %>
Note that if you don't put to_s
, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s
on the date:
<%= "Here is a date: #{my_date}" %>
or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime
as outlined in the other answer.
Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime ("string parse time") with the correct specifier:
Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"
Note that you have to require 'date'
for that to work, then you can call it either as Date.strptime
(if you only care about the date) or DateTime.strptime
(if you want date and time). If you need different formatting, you can call DateTime#strftime (look at strftime.net if you have a hard time with the format strings) on it or use one of the built-in methods like rfc822
.
참고URL : https://stackoverflow.com/questions/11090451/format-the-date-using-ruby-on-rails
'developer tip' 카테고리의 다른 글
Android ImageView 크기가 소스 이미지로 확장되지 않음 (0) | 2020.10.25 |
---|---|
텍스트 상자에 숫자 만 입력 할 수 있습니다. (0) | 2020.10.25 |
터미널에서 작동하는 동안 스택 추적없이 "로컬 호스트의 서버 Tomcat v7.0 서버를 시작하지 못했습니다." (0) | 2020.10.25 |
시작시 단일 양식 숨기기 (0) | 2020.10.25 |
이 간단한 addEventListener 함수 뒤에 'false'가 사용되는 이유는 무엇입니까? (0) | 2020.10.25 |