Kapil
Kapil

Reputation: 1810

Date and Time comparison in Java

I am comparing two date and time but it is not working as expected. Please help me.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Date date1=convertStringToDate("2015-05-03T17:11:00Z");
        Date date2=convertStringToDate("2015-05-08T22:02:20Z");
        System.out.println("Date2:"+date1.compareTo(date2));//output 1

        Date date3=convertStringToDate("2015-05-08T21:15:29Z");
        System.out.println("Date3:"+date1.compareTo(date3));//output -1

        Date date4=convertStringToDate("2015-05-08T19:22:25Z");
        System.out.println("Date4:"+date1.compareTo(date4));//output -1

        Date date5=convertStringToDate("2015-05-08T16:46:31Z");
        System.out.println("Date5:"+date1.compareTo(date5));//output 1

        Date date6=convertStringToDate("2015-05-08T15:48:02Z");
        System.out.println("Date6:"+date1.compareTo(date6));//output 1


    }

     static  Date convertStringToDate(String input){

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd'T'HH:MM:SS'Z'");
        Date date = null;
        try {
            date = formatter.parse(input);

        } catch (ParseException e) {
            e.printStackTrace();
        }


        return  date;
    }
}

Upvotes: 1

Views: 133

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338386

Swap m letters

The comment is correct, you need to fix your format pattern by swapping the uppercase and lowercase m letters.

Better yet, save yourself much pain by avoiding the java.util.Date and .Calendar classes altogether.

ISO 8601

Your input strings are in the standard ISO 8601 format.

Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating textual representations of date-time values. So no need to even define a parsing pattern. Simply feed those strings to the constructor of a DateTime in Joda-Time, or equivalent in java.time.

Avoid old date-time classes

You are using old date-time classes that have proven to be poorly designed and troublesome. Avoid them.

Instead use java.time, or its outmoded predecessor Joda-Time.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

Now in maintenance mode, the Joda-Time project also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

Parse as Instant

Parse directly into Instant objects. An Instant is a moment on the timeline in UTC with a resolution of nanosecond.

Instant a = Instant.parse( "2015-05-03T17:11:00Z" );
Instant b = Instant.parse( "2015-05-08T22:02:20Z" );

Compare with the usual compareTo method.

int comparison = a.compareTo( b );

You can also compare with equals, isBefore, and isAfter methods.

Tip: ISO 8601 strings may have a fractional second with either a dot (period) or a comma as the decimal mark. The java.time classes support the dot by default, so you may want to replace any comma with a dot.

Instant a = Instant.parse( "2015-05-03T17:11:00,123456789Z".replace( "," , "." ) );

Joda-Time

DateTime dateTime_1 = new DateTime( "2015-05-03T17:11:00Z" , DateTimeZone.UTC ) ;
…
Boolean isEarlier = dateTime_.isBefore( dateTime_2 ) ;

Upvotes: 0

Mike M.
Mike M.

Reputation: 39191

Given your test dates, the format String you're passing to the SimpleDateFormat constructor appears to have the lowercase and uppercase m's mixed up. From the docs, uppercase M indicates a month in year character, while a lowercase m indicates minute in hour. Also, you probably want lowercase s's for seconds, instead of uppercase S's, which indicate fractional seconds characters.

It would seem that the format you want is "yyyy-MM-dd'T'HH:mm:ssZ".

Upvotes: 4

Related Questions