I need to check if the time in new york time zone is between 2pm and 1 am but i am not sure how to select the timezone or what to do next
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);
If you're interested in whether the current time is "after or equal to 2pm, or before 1am" then don't need to use string parsing at all. You could use:
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) {
...
}
That's assuming you do want it to match 3pm, but you don't want it to match 8am, for example. That's "between 2pm and 1am" in my view, as per your title.
If you're using Java 8, I'd suggest using LocalTime
instead, via 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) {
...
}
See more on this question at Stackoverflow