Search code examples
javadatesimpledateformatred-black-treedate-comparison

SimpleDateFormat to format one date into another for Red Black Tree? Used together with if statement?


I have a text file full of data that I am putting into a Red Black tree, using the date as the key and the rest of the data from that line as the value. The problem is that some of the dates have this format:

"yyyy-MM-dd"

while some of the other dates have this format:

"M/dd/yyyy"

I need a way to compare these two dates, since I am using them as the key in my Red Black tree, so I need a common format. I'm not sure which would be easier for comparison, but I just know that they need to be in the same format. I've read a bit about SimpleDateFormat, but since I'm thinking of reading through the file, having some sort of if statement to determine if the date is in the wrong format, and then formatting it to the one I want, I'm just not sure how to do that with SimpleDateFormat since I've never used it before. Any help would be appreciated!


Solution

  • java.time

    I recommend that you use java.time, the modern Java date and time API, for your date work.

    If you are reading data from a text file, as soon as possible parse your date strings into LocalDate objects and store those in your red-black tree. For parsing strings in your two formats, if you don’t know in advance which format you get, the following method handles both simply by testing whether the string contains a slash or not.

    private static final DateTimeFormatter DATE_FORMATTER
            = DateTimeFormatter.ofPattern("M/d/y", Locale.ROOT);
        
    /** Parses yyyy-MM-dd or M/d/yyyy */
    private static LocalDate parseDateString(String dateString) {
        if (dateString.contains("/")) {
            return LocalDate.parse(dateString, DATE_FORMATTER);
        } else {
            return LocalDate.parse(dateString, DateTimeFormatter.ISO_LOCAL_DATE);
        }
    }
    

    Let’s try it out:

        System.out.println(parseDateString("2023-11-20"));
        System.out.println(parseDateString("9/18/2019"));
    

    Output:

    2023-11-20
    2019-09-18
    

    Comparison

    LocalDate implements comparable, so you can compare them using compareTo(). For a simple demonstration not involving any tree:

        LocalDate dateFromIso = parseDateString("2023-11-20");
        LocalDate dateFromSlashFormat = parseDateString("9/18/2019");
        LocalDate[] dates = { dateFromIso, dateFromSlashFormat };
        
        System.out.println("Before sort: " + Arrays.toString(dates));
        
        Arrays.sort(dates);
        
        System.out.println("After sort:  " + Arrays.toString(dates));
    
    Before sort: [2023-11-20, 2019-09-18]
    After sort:  [2019-09-18, 2023-11-20]
    

    Tutorial link

    Oracle tutorial: Date Time explaining how to use java.time.