rs79
rs79

Reputation: 2321

Compare disparate Date formats, which are stored as Strings

I have two disparate date formats presented in my application as strings. Here are the formats:

  1. 07/01/2011
  2. 2011-07-01

I'm looking for the most efficient way to assert their equality.

Upvotes: 2

Views: 375

Answers (2)

RMT
RMT

Reputation: 7070

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.

Upvotes: 1

Marcelo
Marcelo

Reputation: 11308

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);

Upvotes: 7

Related Questions