Format Date with getDateTimeInstance() in Java


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 27-Jun-2020

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements