8

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.

Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152

4 Answers4

11

Try this:

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

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

Andrew Feng
  • 1,912
  • 17
  • 20
  • Yes, This works! If you test in `rails console`, at first set the `timezone` in console: `Time.zone = "Dhaka"` – mahfuz Dec 01 '20 at 10:15
6

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")
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52
  • 3
    This doesn't solve the problem. `"2013-01-14 16:06".to_datetime.in_time_zone` results in `Mon, 14 Jan 2013 17:06:00 CET +01:00`, expected result: Mon, 14 Jan 2013 16:06:00 CET +01:00` (16:06 o'clock, not 17:06 o'clock). – Joshua Muheim Jan 14 '13 at 14:54
  • Note that the time you are converting from is not the zone being provided - it's a conversion from the default timezone to the timezone being provided. In this case it's from UTC. – Archonic Mar 05 '20 at 15:13
4

Use in_time_zone:

"2013-01-14 16:06".in_time_zone
=> Mon, 14 Jan 2013 16:06:00 CET +01:00 
Rick Smith
  • 9,031
  • 15
  • 81
  • 85
volix
  • 41
  • 1
0
"2013-01-14 16:06".in_time_zone

Or

"2013-01-14 16:06".in_time_zone

No other answers.

alexey_the_cat
  • 1,812
  • 19
  • 33