SimpleDateFormat Class is used for Parsing ( String to Date ) and Formatting (Date to String ) . It has many methods . For converting String to Date and vice-versa , the following methods are used .
1) parse(String text, ParsePosition pos) - Parses text from a string to convert to a Date
2) format(Date date, StringBuffer toAppendTo, FieldPosition pos) - Formats the given Date into a date/time string(which may be dd/MM/yyyy,dd/MMM/yyyy, yyyyy.MMMMM.dd GGG hh:mm aaa etc ) and appends the result to the given StringBuffer.
The following code converts spring to date and date to string ......
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatParse {
public static void main(String[] args) {
SimpleDateFormat out = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat out1 = new SimpleDateFormat("dd-MMM-yyyy");
System.out.println("String to Date : " + StringToDate(15, 06, 2011) );// which returns a date
System.out.println("String to Date : " + StringToDate("15/06/2011") );// which returns a date
// Now Date is converted into String for printing in a format (dd/mm/yyy or dd/MMM/yyyy)
System.out.println("Date to String : " + out.format (StringToDate(15, 06, 2011) ));// which returns a string
System.out.println("Date to String : " + out1.format (StringToDate("15/06/2011") )); // which returns a string
}
// The following two functions are used to convert string to date (One accepts (dd/mm/yyyy) , another method accepts day, month & year)
public static Date StringToDate(String dateString) // Accepts a Date String and Converts to Date
{
SimpleDateFormat in= new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = in.parse(dateString);
} catch (ParseException e)
{
e.printStackTrace();
}
return date;
}
public static Date StringToDate(int day, int month, int year) // Accepts a Day , Month and Year and Converts to Date
{
SimpleDateFormat in = new SimpleDateFormat("dd/MM/yyyy");
String dateString = day + "/" + month + "/" + year;
Date date=new Date();
try {
date = in.parse(dateString);
} catch (ParseException e)
{
e.printStackTrace();
}
return date;
}
}
Output of the above program :
String to Date : Wed Jun 15 00:00:00 IST 2011
String to Date : Wed Jun 15 00:00:00 IST 2011
Date to String : 15/06/2011
Date to String : 15-Jun-2011
0 comments:
Post a Comment