Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Ruby timestamp to seconds in Epoch and back

I have a field in my database that is stored as a timestamp, I need to output this in seconds in EPOCH time.

like image 721
MichaelScaria Avatar asked Mar 07 '13 05:03

MichaelScaria


People also ask

How do I convert timestamp to epoch?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

Are epoch timestamps always UTC?

Technically, no. Even though epoch time is the means elapsed seconds since 1/1/70 00:00:00 the real "GMT" (UTC) is not. UTC time needed to be changed a few times to take in to account the slowing speed of the rotating earth. As everybody wrote, most people use epoch at UTC.

How is epoch timestamp calculated?

Epoch Time Difference FormulaMultiply the two dates' absolute difference by 86400 to get the Epoch Time in seconds – using the example dates above, is 319080600.


2 Answers

Supposing your timestamp is a Ruby Time object:

puts time_stamp.strftime('%s') puts time_stamp.to_i timestamp = Time.at(628232400) 

In case it is a DateTime object, you have the strftime and strptime methods at your disposal.

like image 121
bert bruynooghe Avatar answered Sep 25 '22 14:09

bert bruynooghe


Returns number of seconds since epoch:

time = Time.now.to_i   

Returns second since epoch which includes microseconds:

time = Time.now.to_f 
like image 24
Sachin R Avatar answered Sep 25 '22 14:09

Sachin R