-1

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

3
  • 1
    m Minute in hour as per javadocs Commented Jun 8, 2017 at 8:13
  • 1
    FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes. See Tutorial by Oracle. Commented Jun 8, 2017 at 10:05
  • To convert "2017-05-02" into "5/2/2017" use LocalDate.parse(yyyyMmDdString).format(DateTimeFormatter.ofPattern("M/d/uuuu")). Commented Jun 8, 2017 at 13:00

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

m - minutes
M - month

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.