Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON datetime?

I am consuming a JSON API that returns datetime values as a string in the following format:

/Date(1370651105153)/

How can I parse a value like this into a datetime variable in rails?

like image 495
startupsmith Avatar asked Dec 01 '25 19:12

startupsmith


1 Answers

That appears to be a UNIX timestamp (seconds since epoch). Additionally it appears to be milliseconds since epoch.

So you can convert it like so - given that value is a String that looks like:

value = "/Date(1370651105153)/"

if value =~ /\/Date\((\d+)\)\//
  timestamp = $1.to_i
  time = Time.at(timestamp / 1000)
  # time is now a Time object
end

You need to divide by 1000 since Time#at expects its argument to be seconds and not milliseconds since the epoch.

like image 197
Cody Caughlan Avatar answered Dec 03 '25 12:12

Cody Caughlan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!