在 Java 中,如何计算截断到午夜的 unix 时间戳?
PHP 示例展示了创建字符串然后将它们解析回来。在 Java 中肯定有比这更干净的方法吗?
Unix 时间戳从 UTC 午夜开始,因此我们可以执行以下操作
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;
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;
对于 unix 时间戳,您可以创建如下函数:
public long getMidnightTimestamp(long timestamp)
{
return timestamp - timestamp % 86400; // 24 * 60 * 60 sec in one day
}
并像这样使用它:
long currentTimestamp = System.currentTimeMillis() / 1000;
long todayMidnightTimestamp = getMidnightTimestamp(currentTimestamp);