Home page

Tuesday, June 20, 2023

Date format in JAVA

In Java, the java.text.SimpleDateFormat class is commonly used to format dates according to specific patterns. The patterns are defined by a combination of letters (such as "yyyy" for the year, "MM" for the month, "dd" for the day) and special characters (such as "/", "-", or ":") that define the desired format. Here are some commonly used patterns to format dates in Java:

"yyyy-MM-dd": Formats the date as "year-month-day" (e.g., 2023-06-03).

"dd/MM/yyyy": Formats the date as "day/month/year" (e.g., 03/06/2023).

"MM/dd/yyyy": Formats the date as "month/day/year" (e.g., 06/03/2023).

"yyyy-MM-dd HH:mm:ss": Formats the date and time as "year-month-day hour:minute:second" (e.g., 2023-06-03 14:30:45).

"EEE, MMM d, yyyy": Formats the date as "day of the week, month day, year" (e.g., Sat, Jun 3, 2023).

Here's an example code snippet that demonstrates formatting a java.util.Date object using SimpleDateFormat:

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateFormatExample {

    public static void main(String[] args) {

        Date date = new Date();

        // Format the date using a specific pattern

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        String formattedDate1 = sdf1.format(date);

        System.out.println("Formatted date (yyyy-MM-dd): " + formattedDate1);

        SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");

        String formattedDate2 = sdf2.format(date);

        System.out.println("Formatted date (dd/MM/yyyy): " + formattedDate2);

        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String formattedDate3 = sdf3.format(date);

        System.out.println("Formatted date and time (yyyy-MM-dd HH:mm:ss): " + formattedDate3);

        SimpleDateFormat sdf4 = new SimpleDateFormat("EEE, MMM d, yyyy");

        String formattedDate4 = sdf4.format(date);

        System.out.println("Formatted date (EEE, MMM d, yyyy): " + formattedDate4);

    }

}

In this example, we create a Date object representing the current date and time.

We define multiple SimpleDateFormat instances with different patterns.

We use the format() method of each SimpleDateFormat instance to format the date according to the specified pattern.

We print the formatted dates to the console.

Output:
Formatted date (yyyy-MM-dd): 2023-06-03
Formatted date (dd/MM/yyyy): 03/06/2023
Formatted date and time (yyyy-MM-dd HH:mm:ss): 2023-06-03 14:30:45
Formatted date (EEE, MMM d, yyyy): Sat, Jun 3, 2023

As shown in the example, the SimpleDateFormat class allows you to format dates according to various patterns to meet your specific requirements.

No comments:

Post a Comment