Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Custom Date Format with SimpleDateFormat class (http://www.go4expert.com/articles/custom-date-format-simpledateformat-t1563/)

pradeep 7Oct2006 14:00

Custom Date Format with SimpleDateFormat class
 

Introduction



A pattern of special characters is used to specify the format of the date. The example below demonstrates some of the characters. For a complete listing, see the javadoc documentation for the SimpleDateFormat class.

Note: This example formats dates using the default locale (which, in the author's case, is Locale.ENGLISH). If the example is run in a different locale, the text (e.g., month names) will not be the same.

The code ...



Code: Java

Format formatter;
       
       // The year
       formatter = new SimpleDateFormat("yy");    // 06
       formatter = new SimpleDateFormat("yyyy")// 2006
       
       // The month
       formatter = new SimpleDateFormat("M");     // 9
       formatter = new SimpleDateFormat("MM");    // 09
       formatter = new SimpleDateFormat("MMM");   // Oct
       formatter = new SimpleDateFormat("MMMM")// October
       
       // The day
       formatter = new SimpleDateFormat("d");     // 9
       formatter = new SimpleDateFormat("dd");    // 09
       
       // The day in week
       formatter = new SimpleDateFormat("E");     // Sat
       formatter = new SimpleDateFormat("EEEE")// Saturday
       
       // Get today's date
       Date date = new Date();
       
       // Some examples
       formatter = new SimpleDateFormat("MM/dd/yy");
       String s = formatter.format(date);
       // 10/29/06
       
       formatter = new SimpleDateFormat("dd-MMM-yy");
       s = formatter.format(date);
       // 29-Oct-06
       
       // Examples with date and time; see also
       // e316 Formatting the Time Using a Custom Format
       formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
       s = formatter.format(date);
       // 2006.10.29.08.36.33
       
       formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
       s = formatter.format(date);
       // Sat, 07 Oct 2006 22:14:02 +0530
 



All times are GMT +5.5. The time now is 11:03.