如何在Java中计算截断到午夜的unix时间戳?
PHP examples显示制作字符串然后再解析它们。肯定会有一种比Java更清晰的方式吗?
答案 0 :(得分: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;
答案 1 :(得分: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;
答案 2 :(得分:3)
对于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);