Site icon JD Bots

How to Format Date and LocalDate in Java?

grayscale photo of computer laptop near white notebook and ceramic mug on table

Photo by Negative Space on Pexels.com

To format Date and LocalDate in specified formats. Refer the below code snippet:

Code

import java.text.SimpleDateFormat;
import java.util.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DemoClass {
    public static void main (String[] args){
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        Date date = new Date();
        System.out.println(formatter.format(date));
        LocalDate now = LocalDate.now();
        System.out.pritln(now.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")));
    }
}

Output

Refer given link for SimpleDateFormat pattern formats:

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Refer given link for DateTimeFormatter pattern formats:

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Thank you All!!! Hope you find this useful.


Exit mobile version