Custom Date Format with SimpleDateFormat class

Discussion in 'Java' started by pradeep, Oct 7, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in

    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:
     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
       
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice