【问题标题】:TimeZone doesn't match up right时区不匹配
【发布时间】:2020-10-01 04:11:48
【问题描述】:

我正在使用 Java 的默认 TimeZoneCalendar 类来尝试获取不同区域的时间,但是当我尝试使用它时,它没有考虑任何 +0x:00。例如,当我输入“欧洲/英格兰”时,它返回 1:30,而实际上是 2:30,因为现在英格兰使用的是 GMT+1,而不是 GMT。

String timeZone = raw.split(" ")[1];
Calendar calendar = new GregorianCalendar();
TimeZone tz;

try {
    tz = TimeZone.getTimeZone(timeZone);
    calendar.setTimeZone(tz);
} catch (Exception e) {
    event.getChannel().sendMessage("Couldn't find time-zone for: " + timeZone +
        ".\n*Usage: !time <continent/city>*\n*You can find TZ names here: " +
        "https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List*").queue();
    return;
}

long hours = calendar.get(Calendar.HOUR_OF_DAY);
String minutes = String.valueOf(calendar.get(Calendar.MINUTE));
if (minutes.length() == 1)
    minutes = "0" + minutes;
User author = event.getAuthor();
event.getChannel().sendMessage(author.getAsMention() + " The current time is: **" + hours + ":" + minutes + "** [" + tz.getDisplayName() + "]").queue();

【问题讨论】:

标签: java date time timezone


【解决方案1】:

我建议您改用现代的date/time API,而不是使用过时的日期/时间 API。

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Europe/London"));
        System.out.println(zdt);
        System.out.println(zdt.getHour());
        System.out.println(zdt.getMinute());

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendLiteral("Hour: ")
                .appendValue(ChronoField.HOUR_OF_DAY)
                .appendLiteral(", Minute: ")
                .appendValue(ChronoField.MINUTE_OF_HOUR)
                .toFormatter();
        System.out.println(formatter.format(zdt));
    }
}

输出:

2020-06-11T14:54:34.081332+01:00[Europe/London]
14
54
Hour: 14, Minute: 54

【讨论】:

  • 时间现在是正确的,但是现在我不能再输入“英格兰”之类的东西了。
  • @AlexHammond Europe/England 不是一个有效的时区 - 我很惊讶旧的 API 接受它。正如您的异常捕获评论所说,“用法:!time city >”,您会注意到它也没有出现在链接的列表中。 “英格兰”不是一座城市; “Europe/London”是英国的正确时区名称,也是您应该使用的名称。
  • 谢谢,Andrzej Doyle。 @AlexHammond - 您可以打印 java.util.TimeZone#getAvailableIDs() 以验证没有时区,例如 Europe/England
  • @AlexHammond 这就是你不应该使用旧 API 的原因。它会默默地拒绝您的无效时区名称并默认为 GMT - 请参阅 javadoc 条目 here -“指定的时区,如果无法理解给定的 ID,则为 GMT 时区。
  • 维基百科有一个list of time zones
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2015-06-05
  • 1970-01-01
  • 2015-01-28
  • 2016-02-06
相关资源
最近更新 更多