6

在 Java 中,如何计算截断到午夜的 unix 时间戳?

PHP 示例展示了创建字符串然后将它们解析回来。在 Java 中肯定有比这更干净的方法吗?

4

3 回答 3

5

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;
于 2013-05-13T06:17:58.810 回答
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;
于 2013-05-13T06:14:43.767 回答
4

对于 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);
于 2016-12-24T23:18:34.107 回答