Search code examples
javaandroiddatetimecalendarutc

Transform and Get DateTime in UTC+0 in android java and compare DateTime's


I read a lot of answers to similar questions, but I couldn't find what I intend to do.

I'm developing an android application that I need to check if the current device DateTime (variable TimeZone) are between two DateTimes (specified in UTC+0).

Here a pseudo example:

if( (UTC+0 DateTime of actual week friday at 23:00:00) 
    < 
    (device DateTime transformed to UTC+0)
    <
    (UTC+0 DateTime of actual week sunday at 23:00:00) )
{
    #some code here
}

I don't know how to obtain the first and third DateTimes, I can get the day with:

Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
if(Calendar.FRIDAY < c.get(Calendar.DAY_OF_WEEK) < Calendar.SUNDAY)

but I still need the DateTime of the actual week friday and sunday at 23:00:00 specified in UTC+0.

I want to transform the actual device DateTime to UTC+0 before the comparision, I tried with Calendar and Joda Time utils but I couldn't find a simple way to obtain the current UTC+0 DateTime and also transform a non UTC+0 DateTime to UTC+0.

I'm sure it must be very simple but can't find the way.


Solution

  • Comparison Methods: isBefore, isAfter, isEqual

    You are working too hard.

    You need not make time zone adjustments when comparing DateTime objects. Joda-Time handles that for you automatically. Internally Joda-Time tracks a DateTime as a number of milliseconds fro the epoch in UTC. So comparing to see which comes before or later is easy.

    Just call the comparison methods on DateTime, isBefore, isAfter, and isEqual.

    Boolean inRange = ( x.isAfter( start ) || x.isEqual( start ) ) && x.isBefore ( stop ) ;
    

    If the DateTime objects happen to all have the same time zone (DateTimeZone), you make use of the handy Interval class.

    Interval interval = new Interval( start , stop ) ;
    Boolean inRange = interval.contains( x ) ;
    

    As for finding the next/last Monday, Sunday, whatever, search StackOverflow as that has been addressed before many times (like this), as have all the topics in your Question actually. Such as this and this and this.

    Both my code above and the Interval class use the "Half-Open" approach in their comparison logic. The beginning is inclusive while the ending is exclusive. Search StackOverflow.com to learn more.