问题
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();
回答1:
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));
}
}
Output:
2020-06-11T14:54:34.081332+01:00[Europe/London]
14
54
Hour: 14, Minute: 54
来源:https://stackoverflow.com/questions/62325706/timezone-doesnt-match-up-right