Format Date with getDateTimeInstance() in Java

Java 8Object Oriented ProgrammingProgramming

To format date, let us see the DateFormat.SHORT as well as DateFormat.LONG constants. Both of them displays different patterns.

Here, we are formatting dates with getDateTimeInstance() method. Use the method to get a date and time format.

For DateFormat.SHORT constant −

DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
System.out.println(dateFormat.format(calendar.getTime()));

For DateFormat.LONG constant −

dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
System.out.println(dateFormat.format(calendar.getTime()));

The following is an example −

Example

 Live Demo

import java.text.DateFormat;
import java.util.Calendar;
public class Demo {
   public static void main(String s[]) {
      Calendar calendar = Calendar.getInstance();
      // for SHORT date-time
      DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
      System.out.println(dateFormat.format(calendar.getTime()));
      // for LONG date-time
      dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
      System.out.println(dateFormat.format(calendar.getTime()));
   }
}

Output

11/22/18 9:57 AM
November 22, 2018 9:57:26 AM UTC
raja
Published on 19-Dec-2018 10:52:22
Advertisements