Formatting a Date Using a Custom Format


 

Formatting a Date Using a Custom Format

In this section, you will learn how to format a date using a custom format.

In this section, you will learn how to format a date using a custom format.

Formatting a Date Using a Custom Format

In this section, you will learn how to format a date using a custom format.

Java has provide many classes that allow a programmer to format the date and time. Here we have used SimpleDateFormat class which is responsible for formatting date and time. It uses unquoted letters from 'A' to 'Z' and from 'a' to 'z' and interpret them as pattern letters for  representing the components of a date or time string. For example,
d-   denotes the day in month
M- denotes the month in year
y-   denotes the year

You can see in the given example, we have created an instance of SimpleDateFormat and specify a format. Then we have called the format() method which includes the date object. This method formats the date into the described pattern.

Here is the code:

import java.text.*;
import java.util.*;

public class FormattingDate {
	public static void main(String[] args) {
		Date date = new Date();
		SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");
		String formattedDate = f.format(date);
		System.out.println("Today's Date is: " + formattedDate);
	}
}

Output:

Today's Date is: 30-09-2010

Ads