Formatting and Parsing a Date for a Locale


 

Formatting and Parsing a Date for a Locale

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

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

Formatting and Parsing a Date for a Locale

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

Java has provide the utility to display the dates in different languages. You can also format and parse those dates. Here we are going to format and parse the date in French language. For this we have used Locale class. This class provides this advantage.

In the given example, we have used Format and SimpleDateFormat class for this purpose. We have specified the Locale and the pattern inside the constructor of the SimpleDateFormat class. Then we have called the format() method that contains the date object. This method returns the date string in a pattern. Now to parse the date, we have used the parseObject() method of Format class and pass the date string into it as an argument. This method parses the text and produce an 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 FormatDateForLocale {
	public static void main(String[] args) throws Exception {
		Locale locale = Locale.FRENCH;
		Format f = new SimpleDateFormat("MMMM d,yyyy", locale);
		String date = f.format(new Date());
		System.out.println("In French, Today's date is: " + date);
		Date d = (Date) f.parseObject(date);
		System.out.println(d.toString());
	}
}

Output:

In French, Today's date is: septembre 30,2010
Thu Sep 30 00:00:00 GMT+05:30 2010

Ads