elkun49
elkun49

Reputation: 133

How to convert UTC time to configured timezone in rails 4

I received a time string from a server and I want to parse or convert that string to configured time zone (Tokyo timezone in my case):

I try to type like this:

Time.zone.parse("2016-05-27T09:00:00.0000000")
but it returns unexpected output:
Fri, 27 May 2016 09:00:00 JST +09:00

Upvotes: 1

Views: 1605

Answers (1)

Matouš Borák
Matouš Borák

Reputation: 15944

If the parsed datetime is a UTC time, add the UTC timezone explicitly to it before parsing:

# this parses the time as local time:    
Time.zone.parse("2016-05-27T09:00:00.0000000")
# => Fri, 27 May 2016 09:00:00 JST +09:00

# this parses the time as UTC and converts to local time:    
Time.zone.parse("2016-05-27T09:00:00.0000000Z")
# => Fri, 27 May 2016 18:00:00 JST +09:00

Note the "Z" appended to the datetime string, meaning that this is a datetime in UTC timezone.

Upvotes: 2

Related Questions