How do you get DateTime.parse to return a time in

2020-08-09 06:49发布

I need this

 require 'date'
 DateTime.parse "Mon, Dec 27 6:30pm"

to return a DateTime for 6:30pm in the EDT timezone, but it returns one in UTC. How can I get a EST DateTime or convert the UTC one into an EDT DateTime with a 6:30pm value?

标签: ruby date
4条回答
倾城 Initia
2楼-- · 2020-08-09 07:46

In Rails, this worked nicely for me

DateTime.parse "Mon, Dec 27 6:30pm #{Time.zone}"

It won't work in vanilla Ruby though.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-08-09 07:47

Final answer ;-)

require 'date'
estHoursOffset = -5
estOffset = Rational(estHoursOffset, 24)
date = (DateTime.parse("Mon, Dec 27 6:30pm") - (estHoursOffset/24.0)).new_offset(estOffset)

(or -4 for EDT)

查看更多
劫难
4楼-- · 2020-08-09 07:49

OK I'm going to offer an answer to my own question

require 'time'
ENV["TZ"] = "US/Eastern"
Time.parse("Mon, Dec 27 6:30pm").to_datetime
=> #<DateTime: 2011-12-27T18:30:00-05:00 (117884327/48,-5/24,2299161)> 
查看更多
地球回转人心会变
5楼-- · 2020-08-09 07:52

DateTime#change()

You can try using change() after parsing it to alter the timezone offset:

DateTime.parse( "Mon, Dec 27 6:30pm" ).change( offset: '-0400' )
# => Wed, 27 Dec 2017 18:30:00 -0400

You can also just use the hours:

DateTime.parse( "Mon, Dec 27 6:30pm" ).change( offset: '-4' )
# => Wed, 27 Dec 2017 18:30:00 -0400

But, be careful, you cannot use an integer:

DateTime.parse( "Mon, Dec 27 6:30pm" ).change( offset: -4 )
# => Wed, 27 Dec 2017 18:30:00 +0000

If you need to determine the correct offset to use based on a time zone you can do something like this:

offset = ( Time.zone_offset('EDT') / 1.hour ).to_s
# => "-4"

DateTime.parse( "Mon, Dec 27 6:30pm" ).change( offset: offset )
# => Wed, 27 Dec 2017 18:30:00 -0400

You can also use change() to manually set other parts of the DateTime as well, like setting the hour to noon:

DateTime.parse( "Mon, Dec 27 6:30pm" ).change( offset: '-4', hour: 12 )
# => Wed, 27 Dec 2017 12:00:00 -0400

Be careful with that one because you can see that it's cleared the minutes as well.

Here's the docs for the change() method: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-change

查看更多
登录 后发表回答