Format and Parse Date in Java

Java 8Object Oriented ProgrammingProgramming

To format a date in Java, firstly import the following package.

import java.text.DateFormat;

Now, create DateFormat object.

DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG);

Use the format() method to format the above dates.

System.out.println(shortFormat.format(new Date()));
System.out.println(longFormat.format(new Date()));

To parse the dates, use the parse() method.

Example

 Live Demo

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class Demo {
   public static void main(String[] args) throws Exception {
      // format date
      DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT);
      DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG);
      System.out.println("Format Date...");
      System.out.println(shortFormat.format(new Date()));
      System.out.println(longFormat.format(new Date()));
      // parse date
      System.out.println("Parse Date...");
      Date d1 = shortFormat.parse("11/21/2018");
      System.out.println(d1);
   }
}

Output

Format Date...
11/22/18
November 22, 2018
Parse Date...
Wed Nov 21 00:00:00 UTC 2018
raja
Published on 10-Dec-2018 16:16:37
Advertisements