我需要检查纽约时区的时间是否在下午2点到凌晨1点之间,但我不知道如何选择时区或下一步做什么
String string1 = "14:00:00";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "01:00:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
答案 0 :(得分:3)
如果您对当前时间是“等于下午2点还是等于凌晨1点”感兴趣,那么根本不需要使用字符串解析。你可以使用:
TimeZone zone = TimeZone.getTimeZone("America/New_York");
Calendar calendar = new GregorianCalendar(zone);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 1 || hour >= 14) {
...
}
假设你做希望它匹配下午3点,但你不希望希望它匹配8am,例如。根据你的头衔,我认为这是“在下午2点到凌晨1点之间”。
如果您使用的是Java 8,我建议您使用LocalTime
代替ZonedDateTime
:
private static final LocalTime EARLY_CUTOFF = LocalTime.of(1, 0);
private static final LocalTime LATE_CUTOFF = LocalTime.of(14, 0);
ZoneId zone = ZoneId.of("America/New_York");
LocalTime time = ZonedDateTime.now(zone).toLocalTime();
if (time.compareTo(EARLY_CUTOFF) < 0 && time.compareTo(LATE_CUTOFF) >= 0) {
...
}
答案 1 :(得分:1)
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
int curr_hour = calNewYork.get(Calendar.HOUR_OF_DAY);
System.out.println(curr_hour < 1 || curr_hour >= 14);