java的系统时间,怎么计算从现在到凌晨还剩下多少时间?

时间:2021-07-07 08:28:41

Apache commons-lang3

long milliSecondsLeftToday = 86400000 -
DateUtils.getFragmentInMilliseconds(Calendar.getInstance(), Calendar.DATE);

System.currentTimeMillis() 是零时区的时间戳,所以你要加上8个小时才行。
最基础的写法:

public class Main {
public static void main(String[] args) {
long hour = 60 * 60 * 1000;
long time = System.currentTimeMillis();
System.out.println(time);
time += 8 * hour;
System.out.println(time);
time %= 24 * hour;
System.out.printf("%02d:%02d\n", time / hour, time % hour / 60000);
time = 24 * hour - time;
System.out.printf("%02d:%02d\n", time / hour, time % hour / 60000);
}
}

在当前时区有夏令时的情况下,另外一个用System.currentTimeMillis() 的答案是不能正确处理的,比如15年美国夏令时从3月8号凌晨2点开始,如果现在时间是3月8号1点,那种方式计算出来的就是错误的,而Calendar API可以正确处理,虽然很难用。

Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis(); c.add(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0); long millis = c.getTimeInMillis() - now;

Java8中的写法

LocalTime midnight = LocalTime.MIDNIGHT;
LocalDate today = LocalDate.now();
LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1);
System.out.println(TimeUnit.NANOSECONDS.toSeconds(Duration.between(LocalDateTime.now(), tomorrowMidnight).toNanos()));

https://www.zhihu.com/question/28475461