Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format LocalDate to string?

Tags:

java

jsr310

People also ask

Can we convert LocalDate to string?

The toString() method of a LocalDate class is used to get this date as a String, such as 2019-01-01. The output will be in the ISO-8601 format uuuu-MM-dd. Parameters: This method does not accepts any parameters. Return value: This method returns String which is the representation of this date, not null.

How do you format a LocalDate?

LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date.


SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.

LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);

That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"


Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

java.time

Unfortunately, all existing answers have missed a crucial thing, Locale.

A date-time parsing/formatting type (e.g. DateTimeFormatter of the modern API or SimpleDateFormat of the legacy API) is Locale-sensitive. The symbols used in its pattern print the text based on the Locale used with them. In absence of a Locale, it uses the default Locale of the JVM. Check this answer to learn more about it.

The text in the expected output, 05.May 1988 is in English and thus, the existing solutions will produce the expected result only as a result of mere coincidence (when the default Locale of the JVM an English Locale).

Solution using java.time, the modern date-time API*:

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

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(1988, 5, 5);
        final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MMMM uuuu", Locale.ENGLISH);
        String output = dtf.format(date);
        System.out.println(output);
    }
}

Output:

05.May 1988

Here, you can use yyyy instead of uuuu but I prefer u to y.

Learn more about the modern date-time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.


System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));

The above answer shows it for today