Vikas
Vikas

Reputation: 669

Comparing dates in java is giving wrong results

I'm comparing dates using following code

String sCreatedDate = "30.07.201514:57:03";
String sModifiedDate = "30.07.201515:40:34";            
SimpleDateFormat parser = new SimpleDateFormat("dd.MM.yyyyHH:MM:SS");

Date d1 = parser.parse(sCreatedDate);
Date d2 = parser.parse(sModifiedDate);         
System.out.println(d1.before(d2));

It printing false, but I'm expecting it to print true.

can you please explain me what I'm doing wrong in this code?

However the above code is working fine for below dates and printing true value:

String sCreatedDate = "23.07.201507:25:35";
String sModifiedDate = "23.07.201507:26:07";

Upvotes: 3

Views: 1204

Answers (1)

SatyaTNV
SatyaTNV

Reputation: 4135

At the end of your format, you've used MM (months) instead of mm (minutes).

String sCreatedDate = "30.07.201514:57:03";
String sModifiedDate = "30.07.201515:40:34";            
SimpleDateFormat parser = new SimpleDateFormat("dd.MM.yyyyHH:mm:ss");//mm small
Date d1 = parser.parse(sCreatedDate);
Date d2 = parser.parse(sModifiedDate);         
System.out.println(d1.before(d2));//true

Upvotes: 9

Related Questions