-2

I need to compare two string dates in java:

String date1 = "2017-05-02";
String date2 = "5/2/2017";
//formatter for the first date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date formattedDate1 = formatter.parse(date1);
//formatter for the second date
formatter = new SimpleDateFormat("m/d/yyyy");
Date formattedDate2 = formatter.parse(date2);
//Wrong results
String formatted1 = formattedDate1.toString(); //Mon Jan 02 00:05:00 EET 2017
String formatted2 = formattedDate2.toString(); //Mon Jan 02 00:05:00 EET 2017

Actually if i compare those 2 i probably will get 'true' but my dates are not the January, it's 'May 5th 2017'.

The other question is that I can't use Date object, I need to actually convert "2017-05-02" into "5/2/2017" and then pass it to another function

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Alex Smoke
  • 619
  • 1
  • 8
  • 18
  • 1
    *m Minute in hour* as per javadocs – Scary Wombat Jun 08 '17 at 08:13
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 08 '17 at 10:05
  • To convert "2017-05-02" into "5/2/2017" use `LocalDate.parse(yyyyMmDdString).format(DateTimeFormatter.ofPattern("M/d/uuuu"))`. – Ole V.V. Jun 08 '17 at 13:00

3 Answers3

5

And because old java date is broken and we all should stop learning that, and since new features in java8 will be helpfull for all us in the future, here another option using javaTime api

String date1 = "2017-05-02";
String date2 = "5/2/2017";
LocalDate d1 = LocalDate.parse(date1, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate d2 = LocalDate.parse(date2, DateTimeFormatter.ofPattern("M/d/yyyy"));

System.out.println(d1);
System.out.println(d2);
System.out.println(d2.isEqual(d1));
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
3

Read the SimpleDateFormat javadoc:

Month is uppercase M:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

...

formatter = new SimpleDateFormat("M/d/yyyy");

Lower case m is minute.

Jens
  • 67,715
  • 15
  • 98
  • 113
0

m - minutes
M - month

Please read date and time patterns http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Max
  • 766
  • 9
  • 19