Post

Ruby Tricks 5 - Adding a Time Zone to a Date Time String

Every now and then, we get data that has a date time string in the local time zone but with no time zone specified. This short note is on how to attach the correct time zone to the data so that it can be used in systems that rely on the time zone.

The problem is common – we might have data that looks like 2020-07-21 16:30 or even like 202007211630 and we want to make it a DateTime object so that it can be used in other places. The normal approach is to use DateTime.parse for this.

>
1
2
3
4
5
require 'net/http'
require 'Date'
txt = '2020-07-21 16:30' # or txt = '202007211630'
ts = DateTime.parse(txt) 
#=> #<DateTime: 2020-07-21T16:30:00+00:00 ((2459052j,59400s,0n),+0s,2299161j)>

You’ll notice that we get this:

#<DateTime: 2020-07-21T16:30:00+00:00 ((2459052j,59400s,0n),+0s,2299161j)>

It correctly parses the time stamp but the time zone is set to UTC since there was no time zone specified. For me, this is wrong since the string refers to a time stamp in the Singapore zone (UTC+8). However, it is surprisingly difficult to change the time zone of a DateTime object. You can’t just set change the zone or the offset from UTC. Support is better in Rails (of course!). It’s best to use something from Rails since it takes care of problems with time zones such as Daylight Saving Time and so on. Fortunately, Singapore is simple since we are on the equator and don’t have any issue with Daylight Saving Time.

If you don’t want to use help from Rails in your Ruby code, there seem to be two ways to handle this: