Formatting and Parsing a Date Using Default Formats - Java Date Time

Java examples for Date Time:Legacy Date Parse

Description

Formatting and Parsing a Date Using Default Formats

Demo Code

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

public class Main {
  public static void main(String[] argv) throws Exception {
    // Format//from   w ww .j a  v  a  2 s  .co m
    Date date = new Date();

    String s = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
    // 2/16/02

    s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
    // Feb 16, 2002

    s = DateFormat.getDateInstance(DateFormat.LONG).format(date);
    // February 16, 2002

    s = DateFormat.getDateInstance(DateFormat.FULL).format(date);
    // Saturday, February 16, 2002

    // This is same as MEDIUM
    s = DateFormat.getDateInstance().format(date);
    // Feb 16, 2002

    // This is same as MEDIUM
    s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
    // Feb 16, 2002

    // Parse
    try {
      date = DateFormat.getDateInstance(DateFormat.DEFAULT).parse(
          "Feb 16, 2017");
    } catch (ParseException e) {
    }
  }
}

Related Tutorials