is there any way to convert the date in java prior to 1970?

786 Views Asked by At

I wanted to convert date in yymmdd format to YYYYMMDD, but when using the simpledateformat class i am getting the years after 1970, but the requirement is of the year which is prior to 1970.

1

There are 1 best solutions below

0
Anonymous On

java.time

Parsing input

The way to control the interpretation of the 2-digit year in yymmdd is through the appendValueReduced method of DateTimeFormatterBuilder.

    DateTimeFormatter twoDigitFormatter = new DateTimeFormatterBuilder()
            .appendValueReduced(ChronoField.YEAR, 2, 2, 1870)
            .appendPattern("MMdd")
            .toFormatter();
    String exampleInput = "691129";
    LocalDate date = LocalDate.parse(exampleInput, twoDigitFormatter);

Supplying a base year of 1870 causes two-digit years to be interpreted in the range 1870 through 1969 (so always prior to 1970). Supply a different base year according to your requirements. Also unless you are sure that input years all across a period of 100 years are expected and valid, I recommend you do a range check of the parsed date.

Formatting and printing output

    DateTimeFormatter fourDigitFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
    String result = date.format(fourDigitFormatter);
    System.out.println(result);

Output in this example is:

19691129

If instead input was 700114, output is:

18700114

Use LocalDate for keeping your date

Instead of converting your date from one string format to another, I suggest that it’s better to keep your date in a LocalDate, not a string (just like you don’t keep an integer value in a string). When your program accepts string input, parse into a LocalDate at once. Only when it needs to give string output, format the LocalDate back into a string. For this reason I have also separated parsing from formatting above.

Link

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