开发者

Wrong date with ruby Date.today and DateTime.now

I've installed ruby-1.8.6-p383 with RVM. System ruby is 1.9.1_p378-1

I'm getting the wrong date from Date.today and DateTime.now when 开发者_高级运维using ruby 1.8.. Whereas Time.now is correct:

irb(main):002:0> DateTime.now.to_s
=> "2126--1-10618T11:23:43+00:00"
irb(main):004:0> Date.today.to_s
=> "2126--1-10618"
irb(main):005:0> Time.now
=> Thu Jan 28 11:55:27 +0000 2010

All is well if I switch to ruby 1.9:

irb(main):003:0> DateTime.now.to_s
=> "2010-01-28T11:58:51+00:00"
irb(main):004:0> Date.today.to_s
=> "2010-01-28"
irb(main):005:0> Time.now
=> 2010-01-28 11:59:05 +0000

Any advice on how to get DateTime to work properly in ruby 1.8 would be most appreciated!


I stumbled upon similar problem and got 3 different solutions, which i tried 2 of and both worked. Read more about it from here:

http://www.ruby-forum.com/topic/210647

Jarmo


The returned string seems to be very broken: i) the year is 2126, ii) there's two hyphens between the year and the month, and ii) the day is 10618.

What platform are you on? What timezone are you on (the example implies you're in GMT)?

I'm on WinXP and Ruby 1.8.6-p111 gives the same result in all three cases.

Edit: I did some digging in the Ruby source code (Date and DateTime are defined in lib/date.rb).

It turns out that Date.today calls internally Time.now.__send__(:to_date)..., so maybe you should try calling Time.now.__send__(:to_date).to_s in irb and compare the output to Time.now.to_s in order to narrow down the problem.

Date.today also calls .new_start(...) on the created Date instance so maybe that's messing up the date in your case.


Im not sure if you are running things locally, or on the server, but I think ruby might be taking the server date, which may be in a different time zone than you are, and thus, appear differently.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜