Search code examples
ruby-on-railsrubytimezonedatetimeoffsetstrptime

Strptime with Timezone


I have a String which I parse with DateTime.strptime. The Timezone of the Date in the String is CET but Ruby creates an UTC DateTime object which of course has an offset of 2hrs.

Currently I'm working around the issue with DateTime.strptime().change(:offset => "+0020") but I'm pretty sure this is not the way it's meant to work.

Can someone enlighten me on the correct way to do this?


Solution

  • I can't delete an accepted answer

    As @LeeJarvis pointed out in the comment section below, Chronic.parse does not accept a :time_class option. So this answer is buggy and while it looks like it works, it doesn't (unless Chronic allows passing a :time_class option soon.)


    The Chronic gem is really powerful.

    I use it like this:

    Chronic.parse("next 5:00 pm", 
    :time_class => ActiveSupport::TimeZone.new(User.first.time_zone)).utc
    

    In my example above, User.first.time_zone is "Pacific Time (US & Canada)".

    Chronic supports a lot of formats so check it out at https://github.com/mojombo/chronic

    Make sure to pass the :time_class option and to convert to UTC (in the documentation, Chronic sets :time_class before calling parse. I avoid this approach because it might cause other parts across the application not to work)

    TimeZone's documentation is at http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html