Parse LocalDateTime format

Viewed 308

Is there a way to parse 2018-09-17T17:13:13.741 to 2018-09-17 17:13:13. I was trying with :

LocalDateTime startDateTime = LocalDateTime.now();
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime.parse(startDateTime, FORMATTER);

With combinations I either get a parse exception or 2018-09-17T17:13:13.

Note: I do not need the T and milliseconds

2 Answers

Use format like this:

LocalDateTime startDateTime = LocalDateTime.now();
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
startDateTime.format(FORMATTER);

instead of DateTimeFormatter you can directly use the LocalDateTime to get a year, month, day, hours, minutes and seconds.

The below code may work for your scenario.

LocalDateTime startDateTime = LocalDateTime.now();
        int year = startDateTime.getYear();
        int month = startDateTime.getMonthValue();
        int day = startDateTime.getDayOfMonth();

        int hours = startDateTime.getHour();
        int minute = startDateTime.getMinute();
        int seconds = startDateTime.getSecond();
        int nanoSeconds = startDateTime.getNano();

        String date = year +"-"+month+"-"+day+" "+hours+":"+minute+":"+seconds;
        System.out.println(date);
Related