Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.to_datetime does not use the current timezone (when none given)

I noticed that Rails' String.to_timezone method does not use the current time zone, when no time zone is given in the string.

$ "2013-01-14 14:38".to_datetime
=> Mon, 14 Jan 2013 14:38:00 +0000
$ DateTime.now
=> Mon, 14 Jan 2013 14:39:50 +0100

Is there a way to tell the method to use the current time zone?

Thanks.

like image 355
Joshua Muheim Avatar asked Jan 14 '13 13:01

Joshua Muheim


3 Answers

Try this:

Time.zone.parse('2013-01-14 14:38').to_datetime

This will use the current timezone to parse the string to date.

like image 73
Andrew Feng Avatar answered Oct 23 '22 21:10

Andrew Feng


There's #in_time_zone method on the DateTime object you can use:

"2013-01-14 14:38".to_datetime.in_time_zone
"2013-01-14 14:38".to_datetime.in_time_zone("Prague")
like image 32
Jiří Pospíšil Avatar answered Oct 23 '22 22:10

Jiří Pospíšil


Use in_time_zone:

"2013-01-14 16:06".in_time_zone
=> Mon, 14 Jan 2013 16:06:00 CET +01:00 
like image 4
volix Avatar answered Oct 23 '22 22:10

volix