开发者

formatting date in ruby

I have 开发者_开发知识库a date in the format 05/22/2011 13:10 Eastern Time (US & Canada)

How can I convert that into a date object? This is what I used to parse the date from sting but I'm getting invalid date error.

str = "05/22/2011 13:10 Eastern Time (US & Canada)"
Date.strptime(str, "%d/%m/%Y %H:%M:%S %Z")


Your sting: 05/22/2011 13:10 Eastern Time (US & Canada).

Here is a number of mistakes in your pattern:

  • Month is a first argument
  • Day is a second
  • Here is no any seconds in your time, only hours and minutes

Also your string includes Date and Time as well, so you'd better to use DateTime class instead of Date class:

Date.strptime(str, "%m/%d/%Y %H:%M %Z")
#=> Sun, 22 May 2011

or

DateTime.strptime(str, "%m/%d/%Y %H:%M %Z")
#=> Sun, 22 May 2011 13:10:00 -0500 

To work with datetime you should require it first:

require 'date'
dt = DateTime.strptime("05/22/2011 13:10 Eastern Time (US & Canada)", "%m/%d/%Y %H:%M %Z")
#=> #<DateTime: 353621413/144,-5/24,2299161>
dt.to_s
#=> "2011-05-22T13:10:00-05:00"
dt.hour
#=> 13
...


There are 2 bugs in your call to Date.strptime

1) The date and month are reversed

2) There is no seconds field in your string

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜