How To Format Time To Today At Midnight GMT In Ruby

12 Dec

I am currently working on creating a Twitter Search Parser that returns the number of @ replies to a specified Twitter user in a given day, so I came across the issue of time. More specifically, I needed to find all the @ reply tweets from yesterday.  I therefore needed to have the time formatted to today and yesterday at midnight.

After searching around the web, I found that Ruby on Rails has a handy way of doing this – all you have to do is put “Time.now.midnight” and it will automatically format the today’s date for you for midnight. I couldn’t find an easy way to do this in Ruby (without the Rails), so here is what I came up with….

require 'time'

#convert today's time to a string
today = Time.now.to_s # => "Mon Dec 12 10:52:45 -0800 2011"

#replace the hours:minutes:seconds and time-zone to the time and time zone that you need
today[11, 14] = "00:00:00 +0000" # => "Mon Dec 12 00:00:00 +0000 2011"

#convert the time string back into time format
Time.parse(today) # => Sun Dec 11 16:00:00 -0800 2011 - The time is adjusted for my time-zone (-0800), but it is equivalent to midnight in GMT time (Mon Dec 12 00:00:00 +0000 2011)

#if you need to, convert the time into a UTC
Time.parse(today).strftime("%s").to_i # => 1323648000

Now, to check and make sure that my time is correct, I used the Epoch Coverter to convert today at midnight GMT into UTC time.

And, as you can see, 13264800 is equivalent to Mon, 12 Dec 2011 00:00:00 GMT 🙂

Let me know if there is a better way to do this conversion in Ruby in the comments!

Advertisements

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