Java date to String, Convert date object into a string with a pattern


 

Java date to String, Convert date object into a string with a pattern

This section illustrates you the conversion of date object into a string pattern.

This section illustrates you the conversion of date object into a string pattern.

Convert date object into a string with a pattern

This section illustrates you the conversion of date object into a string pattern.

Java has provide many classes for formatting and parsing the date and time. Here we have used SimpleDateFormat class. Using this class, you can give different patterns to your dates. 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
h-   denotes hour in am/pm (1-12)
m-  denotes minute in hour
a-   denotes the AM/PM marker

In the given example, we have created an object of SimpleDateFormat class and specified 'MMMM d, yyyy 'at' h:mm a' as a pattern in the constructor of the class. Then we have called the format(date) method of this class which has converted the date into the described pattern.

Here is the code:

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

class DateString {
	public static void main(String[] args) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy 'at' h:mm a");
		String d = sdf.format(date);
		System.out.println(d);
	}
}

Output:

September 28, 2010 at 5:05 PM

Ads