Home > Net >  Parsing milliseconds from a unix date in Ruby
Parsing milliseconds from a unix date in Ruby

Time:06-27

Converting a DateTime to unix convention using %s%L (%s means seconds since Jan 1st 1970, %L means to append 3 digits to represent milliseconds) give this:

DateTime.now.strftime '%s%L'
=> "1656279075654"

How can I get a DateTime back from this?

DateTime.strptime('1656279075654', '%s%L') gives an error, as strptime doesn't seem to know %L strangely.

CodePudding user response:

secs = '1656279075654'.to_f / 1000

DateTime.strptime(secs.to_s, '%s')

or

DateTime.strptime('1656279075654', '%Q')

(%Q - number of milliseconds since 1970-01-01 00:00:00 UTC)

  • Related