How to format date in java?

by madie.koelpin , in category: Java , 2 years ago

How to format date in java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by august.kutch , 2 years ago

@madie.koelpin use SimpleDateFormat to format date to any format in Java, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
        // Today date object
        Date now = new Date();
        // Output: 08-31-2022
        System.out.print(dateFormat.format(now));
    }
}

Member

by wyman , a year ago

@madie.koelpin 

Java provides a built-in library for working with dates called java.time. To format a date in Java, you can use the DateTimeFormatter class from this library.


Here's an example code that formats a date in the pattern "yyyy-MM-dd":

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateFormatExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now(); // get the current date
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // create a formatter with the desired pattern
        String formattedDate = date.format(formatter); // format the date using the formatter
        System.out.println(formattedDate); // output the formatted date
    }
}


This will output something like "2023-03-12" depending on the current date.


You can change the pattern in the ofPattern method to format the date in a different way. For example, "MM/dd/yyyy" would format the date as "03/12/2023".