Convert string dates in java [duplicate]

末鹿安然 提交于 2019-12-02 23:22:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!