Raghuveer
Raghuveer

Reputation: 3067

Parse LocalDateTime format

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

Upvotes: 2

Views: 593

Answers (2)

Hadi
Hadi

Reputation: 17299

Use format like this:

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

Upvotes: 4

Manjunath H M
Manjunath H M

Reputation: 928

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

Upvotes: 0

Related Questions