6

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?

Community
  • 1
  • 1
Will
  • 73,905
  • 40
  • 169
  • 246

3 Answers3

5

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;
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
5

For unix timestamps you can create function like this:

public long getMidnightTimestamp(long timestamp)
{
    return timestamp - timestamp % 86400; // 24 * 60 * 60 sec in one day 
}

And use it like this:

long currentTimestamp =  System.currentTimeMillis() / 1000;
long todayMidnightTimestamp = getMidnightTimestamp(currentTimestamp);
obywatelgcc
  • 93
  • 2
  • 6
  • Leap seconds? This will be slightly imprecise i think. There have been 27 of them since 1970. (OK, forget it. unix time does no do leap seconds. That makes unix time slightly imprecise, but your trick will work 100%) – Karl May 17 '18 at 04:12
  • Smart! A neat workarround without the need to rely on Calendar/Date/SimpleDateFormat – Raste Jun 16 '21 at 16:32
4
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;
David Rabinowitz
  • 29,904
  • 14
  • 93
  • 125