Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Comparing String-Based Date Values in Java Using Common Techniques

Tech 1

Java provides several approaches for comparing dates represented as strings. The choice of method depends on formatting consistnecy and precision requirements.

Lexicographic Comparison with String.compareTo

The compareTo method in String compares characters sequentially using their Unicode values. When date strings share an identical pattern, lexical order matches chronological order.

String firstDate = "2020-07-22";
String secondDate = "2020-06-22";
int resultA = firstDate.compareTo(secondDate); // positive value
int resultB = secondDate.compareTo(firstDate); // negative value

Key constraints:

  • Both inputs must follow the exact same layout (e.g., yyyy-MM-dd). Mixing formats like 2020/01/01 versus 2020-01-01 leads to unpredictable outcomes.
  • When year, month, and day match, additional components such as time affect ordering:
String d1 = "2020/06/22";
String d2 = "2020/05/22 13:01:15";
System.out.println(d1.compareTo(d2)); // positive

String d3 = "2020/06/22";
String d4 = "2020/06/22 13:01:15";
System.out.println(d3.compareTo(d4)); // negative

Lexical comparison is efficient but fragile if input formats diverge.

Converting Strings to Date via SimpleDateFormat

Using SimpleDateFormat, string dates can be parsed into java.util.Date instances for robust comparisons.

Using Date.compareTo

After parsing, invoke compareTo on the resulting Date objects:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
Date start = parser.parse("2020-01-01");
Date earlier = parser.parse("2019-01-01");
int outcome = start.compareTo(earlier); // positive

Behavior mirrors string comparison:

  • Returns a positive integer if the receiver is later.
  • Zero when both represant the same instant.
  • Negative when the receiver precedes the argument.

This approach accommodates more complex patterns before comparison.

Comparing Epoch Milliseconds with getTime()

Each Date instance stores milliseconds since the Unix epoch (1970-01-01T00:00:00Z). Extracting these values enables numeric comparison:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
long millisA = fmt.parse("2019-01-01").getTime();
long millisB = fmt.parse("2020-01-01").getTime();
boolean isALater = millisA > millisB; // false

Numeric millisecond comparison avoids ambiguities from string length or character encoding, making it suitable for programmatic evaluation across vareid formats.

Both Date.compareTo and millisecond comparison require valid parsing; malformed input throws ParseException.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.