简体   繁体   中英

How to Parse Any Datetime format to yyyy-MM-dd in java

I have a date field that is populated dynamically, and I need that field in the format yyyy-MM-dd

For a input date of format 1994-08-01 14:37:44 this is giving a Exception

java.time.format.DateTimeParseException: Text '1994-08-01 14:37:44' could not be parsed, unparsed text found at index 10

This is one of the many other ways I tried LocalDateTime.parse("1994-08-01 14:37:44",DateTimeFormatter.ofPattern(yyyy-MM-dd));

Is there a way to convert all date/datetime to yyyy-MM-dd format?

please help

Thanks

Try it like this. You can extract the LocalDate part.

LocalDate ldt = LocalDateTime.parse("1994-08-01 14:37:44",
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
System.out.println(ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

Prints

1994-08-01

You have a date and time component but you're only using a date format to parse it to a LocalDateTime value, this will fail because LocalDateTime needs the time component in order to work

Start by parsing the full text

String input = "1994-08-01 14:37:44";
LocalDateTime ldt = LocalDateTime.parse(input, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

Then use a DateTimeFormatter to format it the way you want

String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(ldt);
System.out.println(formatted);

which prints

1994-08-01

Depending on your needs, you could also convert the LocalDateTime value to a LocalDate and format it, it's the same result, but you might have need of the LocalDate for other things, who knows...

String formatted = ldt.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM