Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java how to Format Date to yyyy-MM-dd?

Hey there I have a question regarding the way that Java parses or formatts a Date.

I have this code:

private DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, Locale.GERMAN);
private DateFormat dateFormatter2 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        String dateTest = dateFormatter.format(Long.parseLong(pair.getKey().get(3)));
        String dateTest2 = dateFormatter2.format(Long.parseLong(pair.getKey().get(3)));

            System.out.println("dateTest: " + dateTest + " || dateTest2: " + dateTest2);

This gives me following result:

dateTest: Donnerstag, 2. Februar 2023 || dateTest2: 02.02.2023

Now I want to convert the date to this Format: "yyyy-MM-dd". I tried with simpledateformatter and the Parse function but always ended up in Errors like this:

 java.text.ParseException: Unparseable date: "02.02.2023" 

How can I simply change the date to my desired format? Would be cool if the result was of type Date.

DateFormatter only shows me how to do it from a Date but I have a String. The Problem is that I dont know how to change the String into a Date.

new Date(string) and (Date) string do not work.

Edit:

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
            LocalDate date = LocalDate.parse(dateTest2, formatter);
            System.out.println("NewDate " + date); 

result is:

SEVERE: Uncaught Exception
java.time.format.DateTimeParseException: Text '01.02.2023' could not be parsed at index 0

>Solution :

You probably need something like:

LocalDate date = Instant.ofEpochMilli(Long.parseLong(pair.getKey().get(3))).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(date);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading