Home > Blockchain >  Java how to Format Date to yyyy-MM-dd?
Java how to Format Date to yyyy-MM-dd?

Time:02-02

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);

...

        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

CodePudding user response:

You probably need something like:

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

If you have to have Date, you can do:

Date d = Date.from(Instant.ofEpochMilli(Long.parseLong(pair.getKey().get(3))));

CodePudding user response:

If you just need to get a java.util.Date from a long value which is the number of milliseconds since the Unix epoch, it really is trivial:

long millis = Long.parseLong(pair.getKey().get(3));
Date date = new Date(millis);

Or inlined if you really want to:

Date date = new Date(Long.parseLong(pair.getKey().get(3)));

I would strongly advise you to try to migrate all your code to java.time though. It's a far superior API.

  • Related