Reputation: 11
So, I want to compare two dates and I have an if loop to function if one date is after the other. My method:
Start and End Dates are user inputted variables and are in the form Month/Day/Year.
String startDate = "02/20/2012";
String endDate = "03/20/2012";
Date startDate1 = new SimpleDateFormat("MM/dd/yyyy").parse(startDate);
Date endDate1 = new SimpleDateFormat("MM/dd/yyyy").parse(endDate);
however, startDate1 is showing this: Mon Feb 20 00:00:00 EST 2012
and,
endDate1 is showing this: Tue Mar 20 00:00:00 EDT 2012
I don't understand what i'm doing wrong here.
The loop:
if (endDate1.after(startDate1)){
blah blah blah
}
Upvotes: 0
Views: 80
Reputation: 340108
You are seeing correct behavior. The java.util.Date object has both a date portion and a time portion. The object has no time zone yet its toString
method confusingly applies the JVM's default time zone when generating the string.
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use a decent date-time library. For Java, that means either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time, defined by JSR 310).
Joda-Time offers a LocalDate class if you are certain you do not need time or time zone. Caution: Naïve programmers often think they have no need for time or time zone but later regret that decision.
Example code using Joda-Time 2.3.
String startInput = "02/20/2012";
String stopInput = "03/20/2012";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate start = formatter.parseLocalDate( startInput );
LocalDate stop = formatter.parseLocalDate( stopInput );
boolean isStopAfterStart = stop.isAfter( start );
Dump to console…
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "isStopAfterStart: " + isStopAfterStart );
When run…
start: 2012-02-20
stop: 2012-03-20
isStopAfterStart: true
Upvotes: 0
Reputation:
What you specified with MM/dd/yyyy
is the input format to correctly convert user input to a date. What is "shown" (by the debugger ?) is the output format as returned by the toString
method.
But the date is actually stored as an integer number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT.
Upvotes: 0
Reputation: 845
Use this to compare two dates.
if(startDate1.compareTo(endDate1)>0){
System.out.println("Date1 is after Date2");
}else if(startDate1.compareTo(endDate1)<0){
System.out.println("Date1 is before Date2");
}else if(startDate1.compareTo(endDate1)==0){
System.out.println("Date1 is equal to Date2");
}else{
System.out.println("How to get here?");
}
Upvotes: 0
Reputation: 146
You're not doing anything wrong, that's the default toString() representation format of the Date object in java
Upvotes: 2