views:

118

answers:

5

I've been trying Time.parse() and Date.parse(), but can't see to figure it out.

I need to convert a date in the form "2007-12-31 23:59:59" to a UNIX timestamp. Something like PHP's strtotime() function would be perfect.

+2  A: 

You have Time.strptime in Ruby 1.9 So in your case,

>> time = Time.strptime('2007-12-31 23:59:59', '%Y-%m-%d %H:%M:%S')     
=> 2007-12-31 23:59:59 +0000

Once you have a Time object, you can convert it to many formats. A simple time.to_i will give you a Unix Timestamp.

Swanand
+1  A: 

Hi,

You can use 'date.to_time.to_i' to convert date time to unix timestamp.

Following is the output on rails console:-

date = Date.today => Thu, 23 Sep 2010 date => Thu, 23 Sep 2010 date.to_time.to_i => 1285180200

Thanks, Anubhaw

Anubhaw
I should have clarified that I need this to work in rails.
Josh Fraser
Well this works in rails. Following is the out put on rails console >> date = Date.today=> Thu, 23 Sep 2010>> date=> Thu, 23 Sep 2010>> date.to_time.to_i=> 1285180200
Anubhaw
A: 

You can use the strftime method

date = Date.today #this will return Thu, 23 Sep 2010 str_date = date.strftime('%b %d %Y') # This will give Sep 23 2010

refer this for better understanding blog

This will help you to convert time in custom formats. But it won't work in your case i.e converting it to UNIX timestamp.

Rohit
+2  A: 

The ISO 8601 time format for the example you give would be "2007-12-31T23:59:59", not "2007-12-31 23:59:59" (note the T between the data and time components).

In Ruby, if you require the time library, you can parse properly formatted ISO 8601 dates. If your dates are coming in with a space instead of a T to separate the date from the time, just replace it before passing it in to Time.iso8601:

>> require 'time'
=> true
>> Time.iso8601("2007-12-31 23:59:59".sub(/ /,'T'))
=> Mon Dec 31 23:59:59 -0500 2007

To convert a time in this format to a Unix timestamp, just use .to_i:

>> Time.iso8601("2007-12-31 23:59:59".sub(/ /,'T')).to_i
=> 1199163599

If you need more flexibility about the format, Time.parse should do the trick; I would be careful about using that in production code, however, because it might give unexpected values for malformed or invalid input, instead of throwing an exception.

Brian Campbell
A: 

Turned out all I needed was:

Time.parse(date_str).to_i

Josh Fraser