问题
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
回答1:
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.
回答2:
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));
回答3:
m - minutes
M - month
Please read date and time patterns http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
来源:https://stackoverflow.com/questions/44430169/convert-string-dates-in-java