Compare disparate Date formats, which are stored as Strings
I have t开发者_StackOverflow社区wo disparate date formats presented in my application as strings. Here are the formats:
- 07/01/2011
- 2011-07-01
I'm looking for the most efficient way to assert their equality.
Parse both dates using SimpleDateFormat
and then use the equals()
method.
The formats to use will be "MM/dd/yyyy"
and "yyyy-MM-dd"
.
Sample code:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = format1.parse(value1);
Date date2 = format2.parse(value2);
return date1.equals(date2);
You can use a SimpleDateFormat
to make them into Dates
(or Calendar
objects) and compare them like that.
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
MM is the month make sure they are capitalized.
精彩评论