Home Tutorial Java Corejava Javatext Formatting and Parsing a Time for a Locale

 
 

Formatting and Parsing a Time for a Locale
Posted on: October 11, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to format and parse a time for a locale.

Formatting and Parsing a Time for a Locale

In this section, you will learn how to format and parse a time for a locale.

Java has provide several classes for formatting dates, numbers, messages and other objects. These classes helps in translating the binary data into user-readable textual representation of values. For formatting and parsing the time, here we have used DateFormat class. This class formats and parses both date and time for any locale.

To format and parse the time in a particular locale, we have specified 'CANADA'  as the locale 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.util.*;
import java.text.*;

public class FormattingAndParsingTimeForLocale {
	public static void main(String[] args) throws Exception {
		Locale locale = Locale.CANADA;
		String st = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale)
				.format(new Date());
		System.out.println(st);
		Date date = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale)
				.parse(st);
		System.out.println(date.toString());
	}
}

Output:

5:07:18 PM
Thu Jan 01 17:07:18 GMT+05:30 1970

Advertisement

Related Tags for Formatting and Parsing a Time for a Locale:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 11, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com