How to Validate Ordinal Dates?

Viewed 173

My julian date is in 7 digit format YYYYDDD. I want to make sure all the scenarios of leap years should be covered. Currently I have put a check on days. Is there any utility validating it ?

2 Answers

Ordinal date

“Julian” is a misnomer for a date represented as a year with day-of-year number. Ordinal date is a better name.

The misnomer causes confusion as an ordinal date has nothing to do with the Julian calendar. The misnomer likely comes from a misunderstanding of Julian day counting used in astronomy.

DateTimeFormatter

Define a DateTimeFormatter with a custom format. In your custom formatting pattern, use triple uppercase-D, DDD, for day-of-year number.

Attempt to parse your string input. Trap for DateTimeParseException.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuDDD" ) ;
try
{
    LocalDate ld = LocalDate.parse( input ) ;
} 
catch ( DateTimeParseException e )
{
    // handle faulty input
}

ISO 8601

I suggest you educate the publisher of your data about the ISO 8601 format. The standard format for an ordinal date is 8 characters, using a hyphen between the year and the day-of-year number. The DateTimeFormatter class defines that format as a constant: ISO_ORDINAL_DATE. I recommend strongly that you stick to the ISO 8601 formats when exchanging date-time values as text.

For more explanation, see my detailed Answer on similar Question.

I want to make sure all the scenarios of leap years should be covered. Currently I have put a check on days. Is there any utility validating it ?

Yes, simply format the strings to LocalDate using the pattern, uuuuDDD and the leap years will be automatically be taken into consideration by the parsing API.

Demo:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // The 100th day of the year, 2020
        String strDate1 = "2020100";

        // The 100th day of the year, 2019
        String strDate2 = "2019100";

        // Notice 'D' (day-of-year) instead of 'd' (day-of-month)
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuDDD");

        LocalDate date1 = LocalDate.parse(strDate1, dtf);
        LocalDate date2 = LocalDate.parse(strDate2, dtf);

        System.out.println(date1);
        System.out.println(date2);
    }
}

Output:

2020-04-09
2019-04-10
Related