Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a Joda DateTime is, say, between the hours of 4-8pm?

Tags:

java

jodatime

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?

like image 313
LuxuryMode Avatar asked May 15 '12 16:05

LuxuryMode


People also ask

How do I change the timezone in Joda DateTime?

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.

What is the use of Joda-time?

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.

What is Joda-Time API?

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.


1 Answers

Just use getHourOfDay()

int hour = new DateTime().getHourOfDay();
return ((hour >= 16) && (hour < 20))    //4-8pm
        || ((hour >= 0) && (hour < 3)); //12-3am
like image 61
jmruc Avatar answered Sep 20 '22 16:09

jmruc