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!