elkun49 elkun49 - 6 months ago 17
Ruby Question

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):


  • Input: "2016-05-27T09:00:00.0000000"

  • Expected output: Fri, 27 May 2016 18:00:00 JST +09:00



  • 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

    BoraMa BoraMa
    Answer

    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.

    Source (Stackoverflow)

    http://stackoverflow.com/questions/37225353/how-to-convert-utc-time-to-configured-timezone-in-rails-4

    Comments