Wednesday, June 18, 2008

SimpleDateFormat Example in Java

public class DateFormattingTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String myDate="Fri Dec 07 17:58:41 EST 2007";
SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");
try{

Date d1=sdf.parse(myDate);

String s1=sdf2.format(d1);

System.out.println("Date d1 is :"+d1);
System.out.println("Formatted String is :"+s1);

}catch(Exception e){
System.out.println("Date Parsing Exception");

}

}

}


Usage: When you have a String, and if you want to convert it into a java.util.Date,
SimpleDateFormat's instance should indicate the format of your input string for java to parse and convert it into a Date:

Ex: String myDate="Fri Dec 07 17:58:41 EST 2007";

SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");sdf should tell java the format of your input string for it to be able to parse it to a date like:

//Input is a String
//sdf indicates the format of date in i/p String
//Output is a Date


Date d1=sdf.parse(myDate);

Scenario 2: When you have a Date and if you want to convert it into a String,

your SimpleDateFormat object should indicate the format you wish to convert your string into and use format in this case.

ex: SimpleDateFormat sdf2=new SimpleDateFormat("MMM dd yyyy hh:mm:ss:Sa");

//Input is Date
//sdf indicates the format of the String you wish to see it as output
//Output is formatted String


String s1=sdf2.format(d1);

No comments: