【问题标题】:Get difference from current GMT time until 9PM gmt从当前格林威治标准时间到格林威治标准时间晚上 9 点获取差异
【发布时间】:2019-11-25 15:27:33
【问题描述】:

我每分钟都在运行一项任务,我想打印出当前 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 秒?

谢谢。

【问题讨论】:

  • 如果您还可以提及您尝试过的内容,那就太好了。
  • 你好!这可能会帮助您提出一个强有力的问题stackoverflow.com/help/how-to-ask 这样我们可以提供更好的反馈!
  • 用我已有的内容更新了帖子。 @AbhishekGarg
  • 您有使用 Joda-Time 的特别愿望吗?问是因为“Joda-Time 被认为是一个基本上“完成”的项目。没有计划进行重大改进。” (引自the home page)。他们建议“如果使用 Java SE 8,请迁移到 java.time (JSR-310)。”如果使用 Java 6 或 7 也可以。

标签: java time jodatime


【解决方案1】:

如果您至少使用 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);

【讨论】:

  • 感谢您展示现代解决方案。我做了几个简单的测试:它有效。
【解决方案2】:

使用 Joda-Time,您可以使用以下辅助方法获取格林威治标准时间晚上 9 点之前的时间:

import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormat;
public static String timeUntil(int hourOfDay, int minuteOfHour) {
    Period period = Period.fieldDifference(LocalTime.now(DateTimeZone.UTC),
                                           new LocalTime(hourOfDay, minuteOfHour))
                          .plusHours(24).normalizedStandard().withDays(0).withMillis(0);
    StringBuffer buf = new StringBuffer();
    PeriodFormat.wordBased(Locale.US).printTo(buf, period);
    return buf.toString();
}

测试

System.out.println(timeUntil(21, 0)); // until 9 pm GMT
System.out.println(timeUntil(22, 0)); // until 10 pm GMT

样本输出

23 hours, 31 minutes and 48 seconds
31 minutes and 48 seconds

【讨论】:

  • 请注意,此逻辑不处理夏令时,这对于 UTC / GMT 不是问题,但如果您更改为使用其他时区,则可能会出现问题。
猜你喜欢
  • 2013-03-10
  • 2011-05-13
  • 1970-01-01
  • 2010-12-02
  • 2011-10-30
  • 1970-01-01
  • 2013-06-01
  • 2011-02-04
  • 1970-01-01
相关资源
最近更新 更多