JAVA_CAT
JAVA_CAT

Reputation: 859

String Date to LocalDate conversion

My application is giving a Date format and I am trying to convert that string to LocalDate.Here is my code

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateStringUtil {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
        //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        String date ="26 Aug 2019 09:46:09,469";
        LocalDate ld = LocalDate.parse(date, dtf);


    }

}

I am getting error. Any idea how to solve it.

Exception in thread "main" java.time.format.DateTimeParseException: Text '26 Aug 2019 09:46:09,469' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)
at src.DateStringUtil.main(DateStringUtil.java:24)

Upvotes: 1

Views: 2763

Answers (2)

Billy Brown
Billy Brown

Reputation: 2342

Your date time format does not match the input date:

  • Your format expects a date in the dd/MM/yyyy hh:mm pattern: 26/08/2019 09:46.
  • Your date string is a date in the dd MMM yyyy hh:mm:ss,SSS pattern: 26 Aug 2019 09:46:09,469

The Java DateTimeFormatter documentation has more information on the patterns you can use: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Edit: If you then want to output the local date in a different format, create a second DateTimeFormatter and pass it to the format method.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateStringUtil {
    public static void main(String[] args) {
        DateTimeFormatter inputDtf = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss,SSS");
        String date = "26 Aug 2019 09:46:09,469";
        LocalDateTime ld = LocalDateTime.parse(date, inputDtf);

        DateTimeFormatter outputDtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
        String outputDate = ld.format(outputDtf);
    }
}

Upvotes: 1

William Buttlicker
William Buttlicker

Reputation: 6000

You input date should be same of the format specified in DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");

    public static void main(String args[]) {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
    //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
    String date ="26/08/2019 09:46";
    LocalDate ld = LocalDate.parse(date, dtf);

}

You may want to refer this Doc for formats.

Upvotes: 1

Related Questions