Aditya Aditya - 3 months ago 15
Android Question

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;
}
}

Answer

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".