时区不正确 [英] TimeZone doesn't match up right
本文介绍了时区不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Java的默认 TimeZone
和 Calendar
类来尝试获取不同区域的时间,但是当我尝试使用它时,并不需要考虑到任何+ 0x:00.例如,当我输入欧洲/英国"时,它将返回我1:30,而实际上是2:30,因为现在英国使用的是GMT + 1,而不是GMT.
I'm using Java's default TimeZone
and Calendar
classes to try and get the time of different areas, however when I try to use it, it doesn't take into account any +0x:00. For example when I enter "Europe/England" it returns me 1:30, when it's actually 2:30 since right now England is using GMT+1, not 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();
推荐答案
I suggest you switch to modern date/time API instead of using the outdated date/time 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
这篇关于时区不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文