Skip to Content

Formatting date in default formats using DateFormat

  1. /*
  2.   Formatting date in default formats using DateFormat
  3.   This example shows how to format date and time using default formats using Java
  4.   DateFormat class.  Predefined date formats are short, default or medium,  
  5.   long and full.
  6. */
  7.  
  8. import java.text.DateFormat;
  9. import java.util.Date;
  10.  
  11. public class FormattingDateInDefaultFormats {
  12.  
  13.   public static void main(String[] args) {
  14.    
  15.     //create Date object
  16.     Date date = new Date();
  17.  
  18.     //formats date in Short format that consists of numbers like 11/25/06
  19.     String strDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
  20.     System.out.println(strDate);
  21.  
  22.     //formats date in Medium format    
  23.     strDate = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
  24.     /*  
  25.      * We can also use default format instead of MEDIUM like given below
  26.      * strDate = DateFormat.getDateInstance().format(date);
  27.      * OR
  28.      * strDate = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
  29.      */
  30.     System.out.println(strDate);    
  31.  
  32.     //formats date in Long format    
  33.     strDate = DateFormat.getDateInstance(DateFormat.LONG).format(date);
  34.     System.out.println(strDate);
  35.  
  36.     //formats date in Full format
  37.     strDate = DateFormat.getDateInstance(DateFormat.FULL).format(date);
  38.     System.out.println(strDate);
  39.   }
  40. }
  41.  
  42. /*
  43. Typical output would be
  44. 12/27/07
  45. Dec 27, 2007
  46. December 27, 2007
  47. Thursday, December 27, 2007
  48. */