Rails parse date time string in UTC zone

Sometimes we need to parse a date string in UTC timezone in Ruby. Time.parse considers system time zone whereas we might want to parse time in UTC or some other custom timzone. This article helps parse time in UTC or any other zone.

Let’s say, we have a sample datetime string as given below.

datetime = "2018-05-30 18:00"
# => 2018-05-30 18:00:00 +0530

When we parse this string using Time object,

Time.parse(datetime)
# => 2018-05-30 18:00:00 +0530

We can see, the Time.parse parses given datetime string in the system time zone.

Parse using DateTime class

If we parse datetime string using DateTime class, it will by default use UTC timezone.

DateTime.parse(datetime)

DateTime class doesn’t offer flexibility to parse datetime string in particular time zone.

Parse in UTC (or any other) Timezone
Time.find_zone("UTC").parse(datetime)
# => Wed, 30 May 2018 18:00:00 UTC +00:00

We can see the parsed datetime string is parsed in UTC timezone. We can use find_zone to find time in particular zone to use for parsing.