Formatting and Parsing a Date for a Locale - Java Date Time

Java examples for Date Time:Legacy Date Parse

Description

Formatting and Parsing a Date for a Locale

Demo Code

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
  void m() throws Exception {
    Locale locale = Locale.FRENCH;

    // Format with a custom format
    DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
    String s = formatter.format(new Date());
    System.out.println(s);// w w w.ja  v a 2  s.  c o m

    // Format with a default format
    s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale)
        .format(new Date());
    System.out.println(s);

    try {
      // Parse with a custom format
      formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
      Date date = (Date) formatter.parse("mar., 29 janv. 2002");
      System.out.println(date);
      // Parse with a default format
      date = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).parse(
          "29 janv. 2002");
      System.out.println(date);
    } catch (ParseException e) {
    }
  }
}

Related Tutorials