一些ROR时间的说明

It looks like ActiveSupport does provide the parsing methods you are looking for (and I was looking for too), after all! — at least if the string you are trying to parse is a standard, ISO-8601-formatted (:dbformat) date.

If the date you're trying to parse is already in your local time zone, it's really easy!

 > Time.zone.parse('2009-09-24 08:28:43') => Thu, 24 Sep 2009 08:28:43 PDT -07:00  > Time.zone.parse('2009-09-24 08:28:43').class => ActiveSupport::TimeWithZone 

and that time-zone-aware time can then easily be converted to UTC

 > Time.zone.parse('2009-09-24 08:28:43').utc=> 2009-09-24 15:28:43 UTC

or to other time zones:

 > ActiveSupport::TimeZone.us_zones.map(&:name) => ["Hawaii", "Alaska", "Pacific Time (US & Canada)", "Arizona", "Mountain Time (US & Canada)", "Central Time (US & Canada)", "Eastern Time (US & Canada)", "Indiana (East)"]  > Time.zone.parse('2009-09-24 08:28:43').utc.in_time_zone('Eastern Time (US & Canada)') => Thu, 24 Sep 2009 11:28:43 EDT -04:00 

If the date string you're trying to parse is in UTC, on the other hand, it doesn't look like there's any method to parse it directly into a TimeWithZone, but I was able to work around that be first using DateTime.strptime...

If the date you're trying to parse is in UTC and you want it to stay as UTC, you can use:

 > DateTime.strptime('2009-09-24 08:28:43', '%Y-%m-%d %H:%M:%S').to_time=> 2009-09-24 08:28:43 UTC

If the date you're trying to parse is in UTC and you want it converted to your default time zone, you can use:

 > DateTime.strptime('2009-09-24 08:28:43', '%Y-%m-%d %H:%M:%S').to_time.in_time_zone=> Thu, 24 Sep 2009 01:28:43 PDT -07:00 

It looks like it can even parse other formats, such as the strange format that Time#to_s produces:

irb -> Time.zone.parse('Wed, 23 Sep 2009 02:18:08').to_s(:db)     => "2009-09-23 09:18:08" irb -> Time.zone.parse('Wed, 23 Sep 2009 02:18:08 EDT').to_s(:db)     => "2009-09-23 06:18:08" 

I'm quite impressed.

Here are some more examples from [http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html][1]:

  Time.zone = 'Eastern Time (US & Canada)'        # => 'Eastern Time (US & Canada)'   Time.zone.local(2007, 2, 10, 15, 30, 45)        # => Sat, 10 Feb 2007 15:30:45 EST -05:00   Time.zone.parse('2007-02-01 15:30:45')          # => Sat, 10 Feb 2007 15:30:45 EST -05:00   Time.zone.at(1170361845)                        # => Sat, 10 Feb 2007 15:30:45 EST -05:00   Time.zone.now                                   # => Sun, 18 May 2008 13:07:55 EDT -04:00   Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone  # => Sat, 10 Feb 2007 15:30:45 EST -05:00 

More documentation links for reference:

转载于:https://my.oschina.net/u/185728/blog/33993

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值