Formatting and Parsing a Time for a Locale Using Default Formats


 

Formatting and Parsing a Time for a Locale Using Default Formats

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

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

Formatting and Parsing a Time for a Locale Using Default Formats

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

There are different classes for formatting and parsing number, message, date and time and other objects. Using these classes, the data will get translated into more readable form. The class DateFormat is more efficient and easier to use. It formats and parses dates or time in a language-independent manner. It provides four default formatting styles- SHORT, MEDIUM, LONG and FULL.

In the given example, we have defined all the four default formats along the locale 'FRANCE' and invoked the factory method getTimeInstance() which returns the time formatter with the given formatting style for the given locale. The method format() then formats the time. For parsing, we have used parse() method which parses the text.

Here is the code:

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

public class FormattingAndParsingTimeUsingDefaultFormats {
	public static void main(String[] args) {
		Locale l = Locale.FRANCE;
		Date date = new Date();
		String shortTime = DateFormat.getTimeInstance(DateFormat.SHORT, l)
				.format(date);
		System.out.println("Time in short style pattern: " + shortTime);
		String mediumTime = DateFormat.getTimeInstance(DateFormat.MEDIUM, l)
				.format(date);
		System.out.println("Time in medium style pattern: " + mediumTime);
		String longTime = DateFormat.getTimeInstance(DateFormat.LONG, l)
				.format(date);
		System.out.println("Time in long style pattern: " + longTime);
		String fullTime = DateFormat.getTimeInstance(DateFormat.FULL, l)
				.format(date);
		System.out.println("Time in full style pattern: " + fullTime);
		try {
			date = DateFormat.getTimeInstance(DateFormat.FULL, l).parse(
					fullTime);
			System.out.println(date.toString());
		} catch (ParseException e) {
		}
	}
}

Output:

Time in short style pattern: 17:47
Time in medium style pattern: 17:47:06
Time in long style pattern: 17:47:06 GMT+05:30
Time in full style pattern: 17 h 47 GMT+05:30
Thu Jan 01 17:47:00 GMT+05:30 1970

Ads