Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute the unix timestamp for the previous midnight

Tags:

java

datetime

How can you, in Java, compute the unix timestamp truncated to midnight?

PHP examples show making strings and then parsing them back. There has to be a cleaner way to do it in Java than that, surely?

like image 594
Will Avatar asked May 13 '13 06:05

Will


People also ask

How Unix timestamp is calculated?

The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the unix time stamp is merely the number of seconds between a particular date and the Unix Epoch.

What is timestamp in Unix format?

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).

Is Unix timestamp same for all timezones?

The UNIX timestamp is the number of seconds (or milliseconds) elapsed since an absolute point in time, midnight of Jan 1 1970 in UTC time. (UTC is Greenwich Mean Time without Daylight Savings time adjustments.) Regardless of your time zone, the UNIX timestamp represents a moment that is the same everywhere.


2 Answers

Unix timestamp starts from midnight UTC so we can do the following

Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long unixTimeStamp = c.getTimeInMillis() / 1000;
like image 159
Evgeniy Dorofeev Avatar answered Sep 30 '22 09:09

Evgeniy Dorofeev


Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(Calendar.HOUR,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);

long midnightUnixTimestamp = c.getTime().getTime()/1000;
like image 28
David Rabinowitz Avatar answered Sep 30 '22 09:09

David Rabinowitz