我每分钟运行一个任务,我想打印出当前 GMT 时间和 9PM GMT 之间的差异,我希望它一直运行,所以一旦到达 9PM GMT,它就会重置为 24 小时所以它正在寻找第二天晚上 9 点(格林威治标准时间)。
我安装了 jodatime 库
我已经尝试过了,这可以获取当前的 GMT 时间吗?
TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
TimeZone.setDefault(gmtTimeZone);
Calendar calendar = Calendar.getInstance(gmtTimeZone);
现在到 9 点我可以得到小时吗?
if(calendar.get(Calendar.HOUR_OF_DAY); == 9) {
所以我的问题是如何从现在到晚上 9 点(格林威治标准时间)?并很好地格式化 IE; 16 小时 15 分 4 秒?
谢谢。
最佳答案
如果您至少使用 Java 8,我会使用 Java 的 java.time
库方法而不是日历。它们更加友好,并且更难无意中使用错误。
// in a 24 hour clock, 9PM = 21:00
final int ninePM = 21;
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
OffsetDateTime next9PM;
if (now.getHour() >= ninePM) {
next9PM = now.plus(1, ChronoUnit.DAYS)
.withHour(ninePM)
.truncatedTo(ChronoUnit.HOURS);
} else {
next9PM = now.withHour(ninePM)
.truncatedTo(ChronoUnit.HOURS);
}
return Duration.between(now, next9PM);
关于java - 获取与当前 GMT 时间的时差,直至晚上 9 点(gmt),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57064950/