Friday, February 23, 2007

Converting Strings to Dates in Java

grrrr.. it took me a long time to realize there is a way of doing it. :)

Here is how u make dates from Strings in java.


String datefromTable="23 Feb 2007 13:23:43";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");

String fromFile="22 Feb 2007 13:23:43";

java.util.Date d=null;
java.util.Date d2=null;
try{
d=sdf.parse(datefromTable);
d2=sdf.parse(fromFile);
}catch(Exception e){

e.printStackTrace();
}

System.out.println("Compare Dates : "+d.compareTo(d2));
System.out.println("Date value is :"+d);

Major advantage of doing this is you can you java's built in compare to method to compare dates and process accordingly hehe.. lazy to write my own comare to method for strings :)

No comments: