Formatting and Parsing a Date Using Default Formats


 

Formatting and Parsing a Date Using Default Formats

In this section, you will learn how to format and parse a Date using default formats.

In this section, you will learn how to format and parse a Date using default formats.

Formatting and Parsing a Date Using Default Formats

In this section, you will learn how to format and parse a Date using default formats.

Java has provide many classes to format a date. Here we are discussing default formats. The class DateFormat provides this utility. It introduces four default formats for formatting and parsing dates. These are SHORT, MEDIUM, LONG and FULL. There is one more default format DEFAULT which is same as MEDIUM.

In the given example, first of all, we have created an instance of Date class in order to format the date. Then we have used getDateInstance() method to get the normal date format. This method gets the date formatter with the given formatting style. The format() method then takes the Date object and format the date into date string. As we have defined all the default formats so the date will get displayed in all the formats.

Now to parse the date, we have used the parse() method of DateFormat class and pass the date string into it as an argument. This method parses the text to produce Date object. Then we have used toString() method to convert the date object into string.

Here is the code:

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

public class FormattingDatesUsingDefaultFormats {
	public static void main(String[] args) {
		Date date = new Date();
		String shortDate = DateFormat.getDateInstance(DateFormat.SHORT).format(
				date);
		System.out.println("Date in short style pattern: " + shortDate);
		String mediumDate = DateFormat.getDateInstance(DateFormat.MEDIUM)
				.format(date);
		System.out.println("Date in medium style pattern: " + mediumDate);
		String longDate = DateFormat.getDateInstance(DateFormat.LONG).format(
				date);
		System.out.println("Date in long style pattern: " + longDate);
		String fullDate = DateFormat.getDateInstance(DateFormat.FULL).format(
				date);
		System.out.println("Date in full style pattern: " + fullDate);
		try {
			date = DateFormat.getDateInstance(DateFormat.FULL).parse(fullDate);
			System.out.println(date.toString());
		} catch (ParseException e) {
		}
	}
}

Output:

Date in short style pattern: 10/1/10
Date in medium style pattern: Oct 1, 2010
Date in long style pattern: October 1, 2010
Date in full style pattern: Friday, October 1, 2010
Fri Oct 01 00:00:00 GMT+05:30 2010

Ads