1

How can I parse this String

3030821  

to date like

303-08-21 

I mean AD year (Anno Domini),

I would also like this solution to be resistant to String like 20200820

merc-angel
  • 394
  • 1
  • 5
  • 13

1 Answers1

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

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.parse("3030821", DateTimeFormatter.ofPattern("uuuMMdd"));
        System.out.println(date.format(DateTimeFormatter.ofPattern("u-MM-dd")));

        date = LocalDate.parse("20200820", DateTimeFormatter.ofPattern("uuuMMdd"));
        System.out.println(date.format(DateTimeFormatter.ofPattern("u-MM-dd")));
    }
}

Output:

303-08-21
2020-08-20

Learn more about the modern date-time API at Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I would also like this solution to be resistant to String like 20200820 – merc-angel Oct 16 '20 at 21:12
  • 1
    @erickson - Got it! Thank you for the suggestion. Reverted to the original solution. – Arvind Kumar Avinash Oct 16 '20 at 21:25
  • For other visitors to this answer, I found the following helpful: [What is the difference between `u` and `y` (and `Y`) in those datetime formatter strings?](https://stackoverflow.com/questions/29014225/what-is-the-difference-between-year-and-year-of-era). – andrewJames Oct 16 '20 at 21:30