Java Program to format time with DateFormat.MEDIUM

Java 8Object Oriented ProgrammingProgramming

Use the getTimeInstance() method in Java to get the time format for the locale you have set. DateFormat.MEDIUM is a constant for medium style pattern.

Firstly, we will create a Date object −

Date dt = new Date();
DateFormat dateFormat;

Let us format time for a different locale with DateFormat.MEDIUM

dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA);
System.out.println("Locale CANADA = " + dateFormat.format(dt));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
System.out.println("Locale ITALY = " + dateFormat.format(dt));

The following is an example

Example

 Live Demo

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Demo {
   public static void main(String args[]) {
      Date dt = new Date();
      DateFormat dateFormat;
      // Displaying time with MEDIUM constant
      dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.FRENCH);
      System.out.println("Locale FRENCH = " + dateFormat.format(dt));
      dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.GERMANY);
      System.out.println("Locale GERMANY = " + dateFormat.format(dt));
      dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINESE);
      System.out.println("Locale CHINESE = " + dateFormat.format(dt));
      dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA);
      System.out.println("Locale CANADA = " + dateFormat.format(dt));
      dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
      System.out.println("Locale ITALY = " + dateFormat.format(dt));
      dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.TAIWAN);
      System.out.println("Locale TAIWAN = " + dateFormat.format(dt));
   }
}

Output

Locale FRENCH = 09:47:50
Locale GERMANY = 09:47:50
Locale CHINESE = 9:47:50
Locale CANADA = 9:47:50 AM
Locale ITALY = 9.47.50
Locale TAIWAN = 上午 09:47:50
raja
Published on 19-Dec-2018 10:31:23
Advertisements