Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timestamp of most recent midnight from timestamp

Tags:

ruby

I have a timestamp

timestamp = Time.now.utc.to_f

I need to find the timestamp at midnight UTC the same day:

t = Time.at timestamp
Time.at(((t - t.hour * 3600).to_f / 3600).to_i * 3600).to_f

is there a way to get the same timestamp without having to convert the original timestamp to Time object? In a way similar to getting a timestamp rounded to the most recent hour:

(timestamp / 3600).to_i * 3600
like image 682
akonsu Avatar asked Dec 22 '25 17:12

akonsu


1 Answers

Since the UTC timestamp starts on January 1, 1970 at midnight UTC, just do:

timestamp - timestamp % (3600*24)

That will give you the timestamp at the last midnight UTC.

To adjust for your time zone, just add or remove the corresponding number of hours before calculating the modulo and then add or remove them back to get the corresponding UTC timestamp.

like image 141
zakinster Avatar answered Dec 24 '25 09:12

zakinster