Arnab
Arnab

Reputation: 195

Unable to parse date using DateTimeFormatter

I am trying to parse a date string returned to me from DB to LocalDate using DateTimeFormatter. I am receiving the below exception.

String date = "2018-05-16 03:39:13.0";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime localDate= LocalDateTime.parse(date , formatter);

java.time.format.DateTimeParseException: Text '2018-05-16 03:39:13.0' could not be parsed at index 20
        at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) [rt.jar:1.8.0_171]
        at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) [rt.jar:1.8.0_171]
        at java.time.LocalDateTime.parse(LocalDateTime.java:492) [rt.jar:1.8.0_171]

However the below code is working.

String date = "2018-05-16 03:39:13.0";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date newDate= formatter.parse(date);

Upvotes: 3

Views: 4437

Answers (3)

Ram
Ram

Reputation: 1803

If your intent is just to parse the String to LocalDateTime, this will work fine.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");

Upvotes: 0

Flown
Flown

Reputation: 11750

Since you are using the fraction-of-seconds with fixed length of 3, it cannot be parsed with only one digit. Better use a DateTimeFormatterBuilder and implement variable fraction-of-second.

String date = "2018-05-16 03:39:13.0";

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
DateTimeFormatter formatter = builder.appendPattern("yyyy-MM-dd HH:mm:ss")
    .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
    .toFormatter();

LocalDateTime localDate = LocalDateTime.parse(date, formatter);
System.out.println(formatter.format(localDate));

It could also be done by using optional fields to get variable fraction-of-second length:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS][.SS][.S]");

Upvotes: 4

Lucifer
Lucifer

Reputation: 842

Well this might do your job.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateFormateer {
    public static void main(String[] args) throws ParseException{
        String date = "2018-05-16 03:39:13.0";      
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.a", Locale.US);
        Date newDate= formatter.parse(date);
        String date1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.a", Locale. getDefault()). format(newDate);
        Date t=ft.parse(date1);
        ft.applyPattern("yyyy-MM-dd HH:mm:ss.SSS");
        System.out.println(date);
        System.out.println(ft.format(t));
        }
}

Upvotes: -1

Related Questions