Convert LocalDate object to dd/MM/yyyy string format

You can convert LocalDate object to dd/MM/yyyy using atStartOfDay() methods of LocalDate class. There are two ways to convert LocalDate to dd/MM/yyyy string. Let’s see those in the below example.

LocalDate to dd/MM/yyyy string

package com.sneppets.solution;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;

public class LocalDateToddMMyyyyExample {
	
	public static void main (String[] args) {
		
		LocalDate localDate = LocalDate.now();
		System.out.println("LocalDate now() : " + localDate);
		SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		
		//First convert localdate to date using any one of the approach below	
		//i) date from ZonedDateTime - atStartOfDay(ZoneId zone)
		Date dateFromZonedDateTime = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
		
		//ii) date from LocalDateTime - atStartOfDay()		
		Date dateFromLocalDateTime = Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.UTC));
		
		String fmtDateFromZonedDateTime = formatter.format(dateFromZonedDateTime);
		String fmtDateFromLocalDateTime = formatter.format(dateFromLocalDateTime);
		System.out.println("Local date in dd/MM/yyyy using atStartOfDay(ZoneId zone): " + fmtDateFromZonedDateTime);
		System.out.println("Local date in dd/MM/yyyy using atStartOfDay(): " + fmtDateFromLocalDateTime);
	}

}

Output

LocalDate now() : 2019-11-15
Local date in dd/MM/yyyy using atStartOfDay(ZoneId zone): 15/11/2019
Local date in dd/MM/yyyy using atStartOfDay(): 15/11/2019

For instance, first convert the LocalDate object to Date object using either atStartOfDay(ZoneId zone) method whose return type is ZonedDateTime. Otherwise you can use atStartOfDay() method whose return type is LocalDateTime.

//aprroach 1
Date dateFromZonedDateTime = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
		
//approach 2	
Date dateFromLocalDateTime = Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.UTC));

Then use SimpleDateFormat class for formatting and parsing dates in a locale sensitive way.

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date dateFromZonedDateTime = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
String fmtDateFromZonedDateTime = formatter.format(dateFromZonedDateTime);
System.out.println("Local date in dd/MM/yyyy using atStartOfDay(ZoneId zone): " + fmtDateFromZonedDateTime);

Further Learning

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments