Java Date parse and format for Locale

Description

Java Date parse and format for Locale

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

public class Main {
  public static void main(String[] argv) 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);/*  ww  w  .  j  av  a 2s  .  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. 2020");
      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) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related