Archive for June, 2006

Timezones, MySQL and Ruby

Posted in Uncategorized on June 11th, 2006 by Bergo

I have two problems, MySQL wasn’t storing Timezone information and Active::Record is automagically loading objects with TIMESTAMP as a localtime, and not the UTC time that it is.

This problem came about because at work we’re getting two different sources of events to log, with more than one timezone (Australian EST and UTC). I first came across this in February, and it surfaced again a couple of weeks back so I thought I’d record how I solved the problem (for me anyway).

The following little piece lets ActiveRecord know that we stored them in UTC, and retrieve the timestamps accordingly. [ruby] ActiveRecord::Base.default_timezone = :utc [/ruby] Simple as that.

Placing this inside the Model file fixes the localtime problem, now I know it will be UTC and can format the time when I need to.

Parsing a datestring to UTC just did not seem simple enough

[ruby] def parsetoutc( somedatestring )

    parsed_time = ParseDate.parsedate(some_date_string)

    a_time =  Time.gm(*parsed_time)
    dt =  DateTime.parse(some_date_string)
    new_time = a_time

    if dt.zone != 'Z'

        hours = dt.zone[1,2].to_i
        minutes = dt.zone[3,4].to_i
        total = (hours * 60 * 60) + (minutes * 60)

        if dt.zone[0].chr == '+'
            new_time = Time.utc(*parsed_time) - total
        elsif dt.zone[0].chr == '-'
            new_time = Time.utc(*parsed_time) + total
        end

    end

    return new_time

end [/ruby]

This above block seems to work, but there must be an easier way of doing this?

Information resources: