Search This Blog

Tuesday, April 6, 2010

How to formate date into user defined patterns?

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. All that you need to do is provide the date format string along with the constructor. You can find the format letters in SimpleDateFormat javadocs. For example we have given few formats below:

Date and Time PatternResult
"yyyy.MM.dd G 'at' HH:mm:ss z"

2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"Wed, Jul 4, '01
"h:mm a"12:08 PM

"hh 'o''clock' a, zzzz"12 o'clock PM, Pacific Daylight Time
"K:mm a, z"0:08 PM, PDT


The sample code also given below for your reference.

Sample Code:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatter {
   
    public static void main(String a[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
        System.out.println("yyyy.MM.dd G 'at' HH:mm:ss z  ---> "+sdf.format(new Date()));
        sdf = new SimpleDateFormat("hh 'o''clock' a, zzzz");
        System.out.println("hh 'o''clock' a, zzzz  ---> "+sdf.format(new Date()));
    }
}


Output:

yyyy.MM.dd G 'at' HH:mm:ss z  ---> 2010.04.06 AD at 19:30:50 IST
hh 'o''clock' a, zzzz  ---> 07 o'clock PM, India Standard Time

1 comment: