Thursday 14 July 2022

Convert the date string yyyy-MM-dd to dd-MM-yyyy in Java?

Using 'DateTimeFormatter' we can convert the date yyyy-MM-dd to dd-MM-yyyy.

 

'DateTimeFormatter' use below symbols to represent year, month and date.

a.   yyyy or uuuu – represent the year like 2022

b.   MM or LL – Represent month of the year

c.    dd – Represent day of the month

 

Follow below step-by-step procedure to convert the date yyyy-MM-dd to dd-MM-yyyy

 

Step 1: Get the instance of LocalDate by parsing the given date string.

final LocalDate localDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

Step 2: Get DateTimeFormatter instance for the pattern "dd-MM-yyyy".

final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");

Step 3: Format the localDate object created in step 1.

dateTimeFormatter.format(localDate);

 

Find the below working application.

 


DateFormatterDemo.java

 

package com.sample.app;

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

public class DateFormatterDemo {

	private static final String convert(final String dateStr) {
		final LocalDate localDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
		return dateTimeFormatter.format(localDate);

	}

	public static void main(String[] args) {

		String date = "2022-07-14";
		String convertedDate = convert(date);

		System.out.println("date : " + date);
		System.out.println("convertedDate : " + convertedDate);

	}

}

Output

date : 2022-07-14
convertedDate : 14-07-2022

Reference

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/time/format/DateTimeFormatter.html 

 




 

Previous                                                 Next                                                 Home

No comments:

Post a Comment