Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing date strings in Java [duplicate]

Tags:

java

date

So I am using dateString1.compareTo(dateString2) which does a lexicographic comparison with strings, based on the Unicode value of each character, and returns an int. Here is a code sample.

String dateString1 = "05-12-2012";
String dateString2 = "05-13-2012";
if (dateString1.compareTo(dateString2) <=0){
   System.out.println("dateString1 is an earlier date than dateString2");
}

Is this a wrong approach to compare dates in Java?

In my tests, I have not run into a situation where I have gotten unexpected result. I really do not want to create a Date object out of the string, if I don't have to, because I am doing this inside a long running loop.

Ninja Edit Gleaning from the answers below there is nothing wrong with comparing dates as a string if it is in yyyyMMdd format but if it is in any other format it will obviously result in error.

I actually have my date string as yyyyMMdd format in my actual code. (I typed the format wrong in the example I gave above.) So for now, I will just leave the code as it is, and add few lines of comments to justify my decision.

But I now see that comparing strings like this is very limiting and I will run into bugs if dba decides to change the date format down the road, which I don't see happening.

like image 882
pacman Avatar asked May 15 '12 22:05

pacman


People also ask

How do I compare two date strings?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

Can you compare dates as strings?

You can't compare just any date string. For instance, "13-Dec-2020" < "20-Apr-2020" alphabetically but not conceptually. But ISO date strings are neatly comparable, for instance, "2020-12-13" > "2020-04-20" both conceptually and alphabetically.

Can we compare 2 strings using == in Java?

To compare these strings in Java, we need to use the equals() method of the string. You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not.

How do you check if a date is before another date Java?

To compare dates if a date is before another date, use the Calendar. before() method.

How to compare two dates from string in Java?

Parse the date string using the parse () method. The util.Date class represents a specific instant time This class provides various methods such as before (), after () and, equals () to compare two dates Once you create date objects from strings you can compare them using either of these methods as shown below −

How to parse a string to date in Java?

The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string. One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object.

How can I compare two strings in JavaScript?

The simplest and safest way would probably be to parse both of these strings as dates, and compare them. You can convert to a date using a SimpleDateFormat, use the before or after method on the date object to compare them. Show activity on this post.

How to parse dates to compare two different date formats?

In the following example, we have created an instance of the SimpleDateFormat class that allows us to take different date formats. After that, we have taken two variables date1 and date2 of type Date. By using the parse () method of the SimpleDateFormat class, we have parsed the dates to compare. The method returns a date parsed from the string.


3 Answers

Use strings to handle dates in Java is not always the best option. For example, when it is a leap year, February has an extra day. Because strings can be seemingly correct, it is more appropriate to perform a conversion. Java validates that the date is correct.

You can convert strings to dates using the SimpleDateFormat class.

public static void main(String[] args) throws ParseException {
    String dateString1 = "05-12-2012";
    String dateString2 = "05-13-2012";

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Date date1 = format.parse(dateString1);
    Date date2 = format.parse(dateString2);

    if (date1.compareTo(date2) <= 0) {
        System.out.println("dateString1 is an earlier date than dateString2");
    }
}

To find out which parameters are allowed to check Customizing Formats (The Java™ Tutorials > Internationalization > Formatting)

like image 127
Paul Vargas Avatar answered Oct 19 '22 11:10

Paul Vargas


It is bad to use the rules for alphabetization to handle date ordering, mostly because you run into issues where things are ordered differently according to the alphabet and the number system

For the alphabet

01-02-2011 comes before
01-1-2011 (because 0 in the date field is before 1 in the other date field)

For the number system

01, 02, 2011 comes after
01, 1, 2011  because all fields are being compared like numbers

Date objects extend numeric comparison to know which fields take precedence in the comparison, so you don't get a earlier month putting a date "before" another that actually occurs at a latter month but an earlier year.

If you have strict control over the date format, you can align the dates such that they also follow alphabetical rules; however, doing so runs a risk of having your entire program fail in odd ways if you accidentally inject a misformatted date.

The typical way to do this is (not recommended, please use non-String Date comparisons)

YYYYMMDD
(year)(month)(day) all zero-padded.

The last technique is included mainly as you will eventually see it in the wild, and should recognize it for what it is: an attempt to handle dates without a proper date library (aka a clever hack).

like image 30
Edwin Buck Avatar answered Oct 19 '22 10:10

Edwin Buck


As discussed, generally better to work with date-time objects rather than strings.

java.time

The other Answers use old outmoded date-time classes that have proven to be poorly designed, confusing, and troublesome. They lack a class to truly represent a date-only value without time-of-day and without time zone.

Instead use the java.time framework built into Java 8 and later. See Oracle Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

String input = "05-12-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM-dd-yyyy" );
LocalDate ld = LocalDate.parse( input , formatter );

The LocalDate implements compareTo. Also, you can call methods equals, isBefore, isAfter.

Boolean isEarlier = ld.isBefore( someOtherLocalDate );
like image 28
Basil Bourque Avatar answered Oct 19 '22 09:10

Basil Bourque