It's most obvious scenario where you need to convert Date to String and vice versa.
Example : Date to String
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToString {
public static void main(String[] args) {
Date d = new Date();
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String str_dt = df.format(d);
System.out.println("Date : "+str_dt);
}
}
o/p :
Date : 27-Feb-2012
Example : String to Date
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDate {
public static void main(String[] args) throws ParseException {
String d = "27-Jan-2012";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Date date = sdf.parse(d);
System.out.println("Date : "+date);
}
}
o/p :
Date : Fri Jan 27 00:00:00 IST 2012
Date : Fri Jan 27 00:00:00 IST 2012
No comments:
Post a Comment