The Accidental Rubyist

invalid byte sequence in UTF-8

Ruby time conversion with daylight saving

with 3 comments

I had earlier posted that ruby was not taking DST into account when creating a date with EST as the timezone.
Finally got something working thanks to tzinfo. Needs to be installed separately.

 1 #!/usr/bin/env ruby -w
 2 # input may be given as "2:00 PM"  or "14:00"
 3 # http://tzinfo.rubyforge.org/doc/files/README.html
 4 require 'rubygems'
 5 require 'tzinfo'
 6 require 'time'
 7
 8 timestr=ARGV[0];
 9 tz = TZInfo::Timezone.get('America/New_York')
10 tz1 = TZInfo::Timezone.get('Asia/Calcutta')
11 #local = tz.utc_to_local(Time.utc(2008,9,4,14,00,0))
12 local = tz.local_to_utc(Time.parse(timestr))
13 puts tz1.utc_to_local(local)
14 

Please let me know if there is a cleaner way to do this. I should prefer the user to input EST or PST etc and get the correct value, rather than my having to manually edit the code.
source of time convert.
To install tzinfo: sudo gem install tzinfo


$ sudo port upgrade ruby
ruby 1.8.7 (2008-06-20 patchlevel 22) [powerpc-darwin9.4.0]

# substitute (find and replace) “foo” with “bar” on each line
$ cat | ruby -pe ‘gsub(/foo/, “bar”)’

Advertisements

Written by totalrecall

September 4, 2008 at 10:54 pm

Posted in ruby

3 Responses

Subscribe to comments with RSS.

  1. Thanks! Very useful, much more convenient than changing the Time zone globally with Time.zone = “foo”

    BTW from the Rails env you don’t need the require statements, TZInfo::Timezone is available already.

    Moschops

    September 16, 2009 at 5:20 am

  2. […] Ruby time conversion with daylight saving Share this:TwitterFacebookLinkedInLike this:LikeBe the first to like this post. […]

  3. […] Ruby time conversion with daylight saving […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: