How to convert an ISO 8601 date to a UNIX timestamp in Ruby?

I am trying to use Time.parse () and Date.parse () but cannot 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 ideal.

+3
source share
5 answers

You have Time.strptimein 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 an object Time, you can convert it to many formats. Simple time.to_iwill give you a Unix timestamp.

+5
source

ISO 8601 , , "2007-12-31T23: 59: 59", "2007-12-31 23:59:59" ( T ).

Ruby, time, ISO 8601. T, , , Time.iso8601:

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

Unix, .to_i:

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

, Time.parse ; , , , .

+5

'date.to_time.to_i' unix.

rails: -

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

, Anubhaw

+1

strftime

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

. , UNIX.

0
source

It turned out that I needed:

Time.parse (date_str) .to_i

0
source

Source: https://habr.com/ru/post/1766135/


All Articles