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?
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?
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;
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);
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;