Home > Enterprise >  What is the correct way for comparing dates for equality?
What is the correct way for comparing dates for equality?

Time:11-05

I am currently working on the migration to microservice from a legacy API. The legacy API does date comparison for equality by using strings.

Example

String date1FromDataSource1 = "20221110";
String date2FromDataSource2 = "2022-11-10:00:00.000";

String data2FromDataSource2Formatted = formatDateAsPerDataSource1(date1FromDataSource2);

Boolean areDatesEqual = data1FromDataSource1.equals(data2FromDataSource2Formatted);

Should I continue pursuing this way or convert them both to ZoneDateTime and do the date compare.

CodePudding user response:

The implementation doesn't matter.
Only the system tests matter.

There should be enough system tests for the legacy system that if they pass, the service is ready to deploy to production. If there aren't enough, write more until that is true.

System tests are implementation independent and completely portable. Pick the simplest implementation you can think of. If the system tests pass for your new system, your implementation is good.

Unit tests are implementation dependent and should be written too. Quality ensured, with unit and system tests passing and you're good to deploy.

As for a suggestion for an implementation, since you're dealing with strings, you could just compare them as strings.

Here's a starter implementation:

public boolean areSame(String date1, String date2) {
    return yyyymmdd(date1).equals(yyyymmdd(date2));
}

/* @return the first 8 digits found in str */
private String yyyymmdd(String str) {
    return str.replaceAll("\\D", "").substring(0, 8);
}
  • Related