Ruby-on-rails – Time zone in RAILS

If I have a time string in the form of “Wed,22 Jun 2011 09:43:58 0200” from a customer, I want to save the time zone. This is important because it is not only important It is the absolute UTC time, as well as the time zone.

Time.zone.parse(t) will convert the time to the zone that Time.zone is in use at the time, thus losing the source time zone.

Do I have to manually extract the time zone from the string above, or is there an idiomatic way to do this?

DateTime field can only store’YYYY-MM-DD HH:MM:SS’ (MySQL) , There is no time zone information.

You should store the date and time in UTC, and store the time zone in a different field, preferably an integer, specifying the offset from UTC (in minutes Unit).

You can extract the offset like this:

ruby-1.9.2-p180:001:0>> require'active_support /all' # included by Rails by default
# => true
ruby-1.9.2-p180:002:0>> dt = DateTime.parse "Wed, 22 Jun 2011 09:43:58 +0200"
# => Wed, 22 Jun 2011 09:43:58 +0200
ruby-1.9.2-p180:003:0>> dt.utc_offset
# => 7200
ruby-1.9.2-p180:004:0>> dt.utc
# => Wed, 22 Jun 2011 07:43:58 +0000

Edit:

Practice round trip

ruby-1.9.2-p180 :039> u.utc.new_offset(u.offset)
=> Wed, 22 Jun 2011 09:43:58 +0500
ruby-1.9.2-p180 :040> u
=> Wed, 22 Jun 2011 09:43:58 +0500

If I have a time string in the form of “Wed, 22 Jun 2011 09:43:58 0200” from a customer, I want to save the time zone. This is important because it is not only the absolute UTC that is important Time, and time zone.

Time.zone.parse(t) will convert the time to the zone that Time.zone is in use at the time, thus losing the source time zone.

Do I have to manually extract the time zone from the string above, or is there The idiomatic way to do this?

The DateTime field can only store’YYYY-MM-DD HH:MM:SS’ (MySQL), without time zone information.

You should store the date and time in UTC and the time zone in a different field, preferably an integer, specifying the offset from UTC (in minutes).

You You can extract the offset like this:

ruby-1.9.2-p180:001:0>> require'active_support/all' # included by Rails by default
# => true
ruby-1.9.2-p180:002:0>> dt = DateTime.parse "Wed, 22 Jun 2011 09:43:58 +0200"
# => Wed, 22 Jun 2011 09:43:58 +0200
ruby-1.9.2-p180:003:0>> dt.utc_offset
# => 7200
ruby-1.9.2-p180: 004:0>> dt.utc
# => Wed, 22 Jun 2011 07:43:58 +0000

Edit:

Practice round trip

< p>

ruby-1.9.2-p180 :039> u.utc.new_offset(u.offset)
=> Wed, 22 Jun 2011 09:43:58 +0500
ruby-1.9.2-p180 :040> u
=> Wed, 22 Jun 2011 09:43:58 +0500

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3321 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.