Java 8 – How to convert String to LocalDate

Here are a few Java examples of converting a String to the new Java 8 Date API – java.time.LocalDate


  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
  String date = "16/08/2016";

  //convert String to LocalDate
  LocalDate localDate = LocalDate.parse(date, formatter);

The key is understand the DateTimeFormatter patterns

Note
You may interest at this classic java.util.Date example – How to convert String to Date in Java

1. 2016-08-16

If the String is in ISO_LOCAL_DATE format, we can parse the String directly, no need conversion.

JavaDateExample1.java

package com.mkyong.date;

import java.time.LocalDate;

public class JavaDateExample1 {

    public static void main(String[] args) {

        String date = "2016-08-16";

        //default, ISO_LOCAL_DATE
        LocalDate localDate = LocalDate.parse(date);

        System.out.println(localDate);

    }
}

Output


2016-08-16

2. 16-Aug-2016 + Locale.US

2.1 The below program is running fine only if the default locale understands English. For example, Locale.US or Locale.English

JavaDateExample2.java

package com.mkyong.date;

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

public class JavaDateExample2 {

    public static void main(String[] args) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");

        String date = "16-Aug-2016";

        LocalDate localDate = LocalDate.parse(date, formatter);

        System.out.println(localDate);  //default, print ISO_LOCAL_DATE

        System.out.println(formatter.format(localDate)); // print formatter date

    }
}

Output


2016-08-16
16-Aug-2016

2.2 Now, change the locale to Locale.FRANCE, the DateTimeFormatter will fail to parse the Aug and throws DateTimeParseException exception:

JavaDateExample2.java

package com.mkyong.date;

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

public class JavaDateExample2 {

    public static void main(String[] args) {

        // not all default locale is Locale.US
        // simulate a France locale.
        Locale.setDefault(Locale.FRANCE);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");

        String date = "16-Aug-2016";

        LocalDate localDate = LocalDate.parse(date, formatter);

        System.out.println(localDate);

        System.out.println(formatter.format(localDate));

    }
}

Exception in thread "main" java.time.format.DateTimeParseException: Text '16-Aug-2016' could not be parsed at index 3
	at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
	at java.base/java.time.LocalDate.parse(LocalDate.java:428)

2.3 The safest way is always specified a Locale.US for DateTimeFormatter.

JavaDateExample2.java

package com.mkyong.date;

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

public class JavaDateExample2 {

    public static void main(String[] args) {

        Locale.setDefault(Locale.FRANCE);

        // no problem now, DateTimeFormatter always uses Locale.US
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy", Locale.US);

        String date = "16-Aug-2016";

        LocalDate localDate = LocalDate.parse(date, formatter);

        System.out.println(localDate);  //default, print ISO_LOCAL_DATE

        System.out.println(formatter.format(localDate)); // print formatted date

    }
}

Output


2016-08-16
16-Aug-2016

3. 16/08/2016

JavaDateExample3.java

package com.mkyong.date;

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

public class JavaDateExample3 {

    public static void main(String[] args) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");

        String date = "16/08/2016";

        LocalDate localDate = LocalDate.parse(date, formatter);

        System.out.println(localDate);

        System.out.println(formatter.format(localDate));

    }
}

Output


2016-08-16
16/08/2016

4. Tue, Aug 16 2016

JavaDateExample4.java

package com.mkyong.date;

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

public class JavaDateExample4 {

    public static void main(String[] args) {

        // define a locale which understand English words, refer example 2 bug
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, MMM d yyyy", Locale.US);

        String date = "Tue, Aug 16 2016";

        LocalDate localDate = LocalDate.parse(date, formatter);

        System.out.println(localDate);

        System.out.println(formatter.format(localDate));

    }
}

Output


2016-08-16
Tue, Aug 16 2016

5. Tuesday, Aug 16, 2016 12:10:56 PM

This example convert a String to java.time.LocalDateTime

JavaDateExample5.java

package com.mkyong.date;

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

public class JavaDateExample5 {

    public static void main(String[] args) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy hh:mm:ss a", Locale.US);

        String date = "Tuesday, Aug 16, 2016 12:10:56 PM";

        LocalDateTime localDateTime = LocalDateTime.parse(date, formatter);

        System.out.println(localDateTime);

        System.out.println(formatter.format(localDateTime));

    }
}

Output


2016-08-16T12:10:56
Tuesday, Aug 16, 2016 12:10:56 PM

6. 2016-08-16T15:23:01Z

The Z suffix means UTC, convert the String to java.time.instant first, and play around the time with ZonedDateTime.

JavaDateExample6.java

package com.mkyong.date;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class JavaDateExample6 {

    public static void main(String[] args) {

        String dateInString = "2016-08-16T15:23:01Z";

        Instant instant = Instant.parse(dateInString);

        System.out.println("Instant : " + instant);

        //get date time only
        LocalDateTime result = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneOffset.UTC.getId()));

        //get localdate
        System.out.println("LocalDate : " + result.toLocalDate());

        //get date time + timezone
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Tokyo"));
        System.out.println(zonedDateTime);

        //get date time + timezone
        ZonedDateTime zonedDateTime2 = instant.atZone(ZoneId.of("Europe/Athens"));
        System.out.println(zonedDateTime2);

    }
}

Output


Instant : 2016-08-16T15:23:01Z
LocalDate : 2016-08-16
2016-08-17T00:23:01+09:00[Asia/Tokyo]
2016-08-16T18:23:01+03:00[Europe/Athens]

7. 2016-08-16T10:15:30+08:00

The last +08:00 is a timezone. String -> ZonedDateTime -> LocalDate.

JavaDateExample7.java

package com.mkyong.date;

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

public class JavaDateExample7 {

    public static void main(String[] args) {

        String date = "2016-08-16T10:15:30+08:00";

        ZonedDateTime result = ZonedDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME);

        System.out.println("ZonedDateTime : " + result);

        System.out.println("TimeZone : " + result.getZone());

        LocalDate localDate = result.toLocalDate();

        System.out.println("LocalDate : " + localDate);

    }
}

Output


ZonedDateTime : 2016-08-16T10:15:30+08:00
TimeZone : +08:00
LocalDate : 2016-08-16

8. DateTimeParseException

If the date is unable to parse, it will throw DateTimeParseException.

JavaDateExample8.java

package com.mkyong.demo;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;

public class JavaDateExample8 {

    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-MMM-yyyy", Locale.US);

    public static void main(String[] args) {

        try {
            LocalDate localDate = LocalDate.parse("16-ABC-2016", dtf);
            System.out.println(dtf.format(localDate));
        } catch (DateTimeParseException e) {
            System.err.println("Unable to parse the date!");
            //e.printStackTrace();
        }

    }

}

Output


Unable to parse the date!

References

25 comments on “Java 8 – How to convert String to LocalDate

  1. I’d like to thank you for your posts.
    They always save my day.

    Reply
  2. how can I import java.time package it not working plz help me

    Reply
  3. hello,
    I think for 3. 16/08/2016, you need to add “d” in days format, so the program add “0” to the days between [1,9]
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“dd/MM/yyyy”);

    Reply
  4. Hi mkyong,
    My requirement is to convert “ddMMM” formated date to “yyyy-MM-dd”.
    For Example = “30SEP” –> “2019-09-30”
    01JAN –> “2020-01-09” (if the date is in past for current year then take next year)

    Reply
  5. Hello, I have a java.sql.Date in format 2019-02-01. How can I change it to java.sql.Date 01.02.2019?

    Reply
  6. Dude, How to print 20-nov-2018 without any traces of toLowerCase

    Reply
  7. 5. String = Tuesday, Aug 16, 2016 12:10:56 PM
    Here you have a wrong pattern, because “HH” is for 24 hour time. You need “hh” pattern

    Reply
  8. Example 5 doesnt work, the parsing with the formatter is not working.

    Reply
    1. Sorry, It will fail if the default locale is not English.

      The example 5 is updated to specify Locale.US in DateTimeFormatter

      Reply
  9. You left the most important bit out: How do you check for failure in parsing a date?????????

    Reply
  10. Hello, tell me please, how parse date with the format – “dd MMM” (02 Jan)?

    Thanks.. 🙂

    Reply
    1. We can provide a default year like this:

      DateTimeFormatter formatter = new DateTimeFormatterBuilder()
      .appendPattern("dd MMM")
      .parseDefaulting(ChronoField.YEAR, 2020)
      .toFormatter(Locale.ENGLISH);

      String date = "02 Jan";

      LocalDate localDate = LocalDate.parse(date, formatter);

      Reply
  11. you must use
    DateTimeFormatter DTF_DATETIME = DateTimeFormatter.ofPattern(“dd-MMM-yyyy”, Locale.ENGLISH);
    instead of DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“d-MMM-yyyy”);

    Reply
  12. java.time.format.DateTimeParseException: Text ’16-Aug-2016′ could not be parsed at index 3
    It’s wrong… just waste of time by using your site !!!

    Reply
    1. That’s because “Aug” is in English, so you must set a java.util.Locale in the formatter:

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“d-MMM-yyyy”, Locale.US);

      The code without the locale will work only if the JVM default locale is english.

      That’s why I don’t like this site, the examples are very innacurate (don’t work all the times, just for the author’s default configs), without any explanation about why the code works (which is much more important than just “here’s the code, just copy, paste and don’t think about it”) and so on.

      Reply
      1. Thanks for your feedback. Article is updated with locale, and I will be more considerate next time.

        Reply
  13. I have been told that instead of
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“d/MM/yyyy”);
    String date = “16/08/2016”;
    LocalDate localDate = LocalDate.parse(date, formatter);
    I should use
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“d/MM/yyyy”);
    String date = “16/08/2016”;
    LocalDate localDate = formatter.parse(date);

    Reply
    1. formatter.parse returns a TemporalAccessor, while LocalDate.parse returns the correct type (LocalDate).
      Although you can do formatter.parse(date, LocalDate::from), which will also return a LocalDate

      Reply
  14. Add the locale to your examples, otherwise you might get a parse error

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“EEEE, MMM d, yyyy HH:mm:ss a”); // no locale
    String date = “Tuesday, Aug 16, 2016 12:10:56 PM”; // error for “Tuesday” if you are not in the US

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“EEEE, MMM d, yyyy HH:mm:ss a”, Locale.US);
    String date = “Tuesday, Aug 16, 2016 12:10:56 PM”; // no error, everything´s fine

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *