I'd like to check if a given DateTime is between 4am - 8am or between 12am-3am. What would be the right way to go about doing that?
This seems to do the trick:
DateTime start = new DateTime().withHourOfDay(4);
DateTime end = new DateTime().withHourOfDay(8);
Interval interval = new Interval(start, end);
if(interval.contains(now)) return true;
Is there a better way?
Timezone conversionforID( "Europe/London" ); DateTimeZone timeZoneKolkata = DateTimeZone. forID( "Asia/Kolkata" ); DateTimeZone timeZoneNewYork = DateTimeZone. forID( "America/New_York" ); DateTime nowLondon = DateTime. now( timeZoneLondon ); // Assign a time zone rather than rely on implicit default time zone.
Joda-Time provides support for multiple calendar systems and the full range of time-zones. The Chronology and DateTimeZone classes provide this support. Joda-Time defaults to using the ISO calendar system, which is the de facto civil calendar used by the world.
Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java. time package.
Just use getHourOfDay()
int hour = new DateTime().getHourOfDay();
return ((hour >= 16) && (hour < 20)) //4-8pm
|| ((hour >= 0) && (hour < 3)); //12-3am
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With