ABJ
ABJ

Reputation: 309

Java Date Comparison

I am trying to compare dates using java.util.Date and also java.util.Calendar but for some reason I do not seem to get the correct result. My code:

DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
String currentDate = "2014-10-04";
String startDate = "2014-07-08";
String endDate = "2015-02-28";
Calendar cDate = Calendar.getInstance();  
cDate.setTime(df.parse(currentDate));
Calendar sDate = Calendar.getInstance();  
sDate.setTime(df.parse(startDate));
Calendar eDate = Calendar.getInstance();  
eDate.setTime(df.parse(endDate));
System.out.println(cDate.compareTo(sDate));
System.out.println(cDate.after(sDate));

As you can see the after should return true but it returns false.

Upvotes: 0

Views: 141

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 340200

tl;dr

org.threeten.extra.LocalDateRange                      // Represents a pair of `LocalDate` objects as a date range.
.of(
    LocalDate.parse( "2014-07-08" ) ,                  // Parse your input strings. The standard ISO 8601 format is used by default, so no need to specify a formatting pattern.
    LocalDate.parse( "2015-02-28" ) 
)                                                      // Returns a `LocalDateRange` object.
.contains(
    LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )   // Capture the current date as seen in the wall-clock time used by the people of a particular region.
)                                                      // Returns boolean primitive.

false

java.time

The modern approach uses the java.time classes that supplanted the terribly troublesome old date-time classes such as Date/Calendar.

Also, you are using date-with-time types to represent a date-only value. Instead, use the LocalDate date-only class.

Today

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your [desired/expected time zone][2] explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;

Comparing

LocalDate start = LocalDate.parse( "2014-07-08" ) ;
LocalDate stop = LocalDate.parse( "2015-02-28" ) ;

Compare with the isBefore, isAfter, and isEqual methods.

Use Half-Open approach (beginning is inclusive, while ending is exclusive) to define the span-of-time.

Boolean contains = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;

LocalDateRange

If doing much of this work, add the ThreeTen-Extra library to your project. This gives you the LocalDateRange class.

LocalDateRange range = LocalDateRange.of( start , stop ) ;
Boolean contains = range.contains( today ) ;

About java.time

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

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 0

Wendel
Wendel

Reputation: 2977

Do you fix the problem changing "yyyy-mm-dd" to "yyyy-MM-dd" as previously answered.

I run the code:

public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = "2014-10-04";
        String startDate = "2014-07-08";
        String endDate = "2015-02-28";
        Calendar cDate = Calendar.getInstance();
        cDate.setTime(df.parse(currentDate));
        Calendar sDate = Calendar.getInstance();
        sDate.setTime(df.parse(startDate));
        Calendar eDate = Calendar.getInstance();
        eDate.setTime(df.parse(endDate));
        System.out.println(cDate.compareTo(sDate));
        System.out.println(cDate.after(sDate));
    }

And result was:

1
true

Upvotes: 1

Marcelo Keiti
Marcelo Keiti

Reputation: 1240

The problem is in your SimpleDateFormat pattern: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

M   Month in year   
m   Minute in hour

In your code:

cDate = 2014-01-04 00:10:00
sDate = 2014-01-08 00:07:00

You should use:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

Upvotes: 0

chearius
chearius

Reputation: 170

Your pattern for SimpledateFormat is incorrect: mm specifies the minute of the day. Use yyyy-MM-dd and it works.

See http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Upvotes: 4

Related Questions