使用 Ruby on Rails 格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11090451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:34:03  来源:igfitidea点击:

Format the date using Ruby on Rails

ruby-on-railsruby

提问by Alexandre

The flickr api provides a posted date as unix timestamp one: "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."

flickr api 提供发布日期作为 unix 时间戳一:“ 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.

For example, here is the date '1100897479'. How do I format it using Ruby on Rails?

例如,这里是日期“ 1100897479”。如何使用 Ruby on Rails 对其进行格式化?

回答by CMW

Once you have parsed the timestamp string and have a time object (see other answers for details), you can use Time.to_formatted_sfrom Rails. It has several formats built in that you can specify with symbols.

一旦您解析了时间戳字符串并拥有一个时间对象(有关详细信息,请参阅其他答案),您就可以使用Rails 中的Time.to_formatted_s。它内置了多种格式,您可以使用符号指定这些格式。

Quote:

引用:

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 is an alias)

(Time.to_s 是一个别名)

You can also define your own formats - usually in an initializer (Thanks to Dave Newtonfor pointing this out). This is how it's done:

您还可以定义自己的格式 - 通常在初始化程序中(感谢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}") }

回答by Edu Wass

Here's my go at answering this,

这是我回答这个问题的方法,

so 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:

所以首先您需要将时间戳转换为实际的 Ruby 日期/时间。如果您只是从 facebook 接收字符串或整数,则需要执行以下操作:

my_date = Time.at(timestamp_from_facebook.to_i)

OK, so now assuming you already have your date object...

好的,现在假设您已经有了日期对象...

to_formatted_sis a handy Ruby function that turns dates into formatted strings.

to_formatted_s是一个方便的 Ruby 函数,可将日期转换为格式化字符串。

Here are some examples of its usage:

以下是其用法的一些示例:

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"

As you can see: :db, :number, :short... are custom date formats.

如您所见::db, :number, :short... 是自定义日期格式。

To add your own custom format, you can create this file: config/initializers/time_formats.rband add your own formats there, for example here's one:

要添加您自己的自定义格式,您可以创建此文件:config/initializers/time_formats.rb并在那里添加您自己的格式,例如这里有一个:

Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015

Where :month_day_comma_yearis your format's name (you can change this to anything you want), and where %B %e, %Yis unix date format.

其中:month_day_comma_year是您的格式名称(您可以将其更改为任何您想要的名称),其中%B %e, %Y是 unix 日期格式。

Here's a quick cheatsheet on unix date syntax, so you can quickly setup your custom format:

这是有关 unix 日期语法的快速备忘单,因此您可以快速设置自定义格式:

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"

Hope this helped you. I've also made a github gistof this little guide, in case anyone prefers.

希望这对你有帮助。我还制作了这个小指南的github 要点,以防有人喜欢。

回答by Dave Newton

Easiest is to use strftime(docs).

最简单的是使用strftime(docs)

If it's for use on the view side, better to wrap it in a helper, though.

但是,如果它用于视图侧,最好将它包装在一个助手中。

回答by ReggieB

@CMW's answer is bang on the money. I've added this answer as an example of how to configure an initializer so that both Date and Time objects get the formatting

@CMW 的答案是物超所值。我已添加此答案作为如何配置初始值设定项以便日期和时间对象都获得格式的示例

config/initializers/time_formats.rb

配置/初始化程序/time_formats.rb

date_formats = {
  concise: '%d-%b-%Y' # 13-Jan-2014
}

Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats

Also the following two commands will iterate through all the DATE_FORMATSin your current environment, and display today's date and time in each format:

此外,以下两个命令将遍历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(':- ')}

回答by Benjamin Crouzier

Have a look at localize, or l

看看localize,或l

eg:

例如:

l Time.at(1100897479)

回答by Taryn East

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:

首先,您需要将时间戳转换为实际的 Ruby 日期/时间。如果您只是从 facebook 接收字符串或整数,则需要执行以下操作:

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):

然后在视图中很好地格式化它,你可以使用to_s(对于默认格式):

<%= 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_son the date:

请注意,如果您没有 put to_s,如果您在视图或字符串中使用它,默认情况下仍会调用它,例如以下内容也将to_s在日期调用:

<%= "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 strftimeas outlined in the other answer.

或者如果您希望以特定方式格式化日期(例如使用“d/m/Y”) - 您可以strftime按照其他答案中的概述使用。

回答by Michael Kohl

Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime("string parse time") with the correct specifier:

由于时间戳是自 UNIX 时代以来的秒数,您可以使用带有正确说明符的DateTime.strptime(“字符串解析时间”):

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.netif you have a hard time with the format strings) on it or use one of the built-in methods like rfc822.

请注意,您必须使其require 'date'工作,然后您可以将其称为Date.strptime(如果您只关心日期)或DateTime.strptime(如果您想要日期和时间)。如果您需要不同的格式,您可以在其上调用DateTime#strftime(如果您对格式字符串有困难,请查看strftime.net)或使用其中一种内置方法,例如rfc822.