0

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.

Ascalonian
  • 14,409
  • 18
  • 71
  • 103
ABJ
  • 309
  • 2
  • 4
  • 10
  • 3
    `mm` is for minutes. `MM` is for months. – Reimeus Feb 19 '15 at 14:36
  • 3
    @Vicky Don't make code corrections that invalidate the question. – Bill the Lizard Feb 19 '15 at 14:39
  • You also don't need to use Calendar. You can just do: `Date cDate = df.parse(currentDate);`, etc. and then do the same comparison on `cDate.after(sDate)` – Ascalonian Feb 19 '15 at 14:39
  • 1
    @BilltheLizard Yup, answers should be posted as answers, not as edits to the question. :) – xehpuk Feb 19 '15 at 14:42
  • I put it back, but hope she didn't do it to any other questions as well lol – Ascalonian Feb 19 '15 at 14:43
  • Take care about SimpleDateFormat, its not threadsave. – Grim Feb 19 '15 at 14:47
  • Comparing `Dates` in Java is not well build and most people in this case would use `Joda DateTime` to do so. Here a link to the website: http://www.joda.org/joda-time/ – Moduo Feb 19 '15 at 14:52
  • @BilltheLizard: When I did code correction, I did not know the mistake was intentional. I thought its a typo. – Vicky Feb 19 '15 at 15:08
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Aug 10 '18 at 07:01

4 Answers4

4

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

chearius
  • 170
  • 6
1

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
Wendel
  • 2,809
  • 29
  • 28
0

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");
Marcelo Keiti
  • 1,200
  • 9
  • 10
0

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154