Thursday, August 7, 2008

get around Date, blow your date's mind, Customize

This is one sweet utility that I have used over and over again. Honestly I keep forgetting the exact way everytime I need to format date(the java type ;)

Nice to keep it in a little utility program inside the utility package of your project


Example 1:
Date exampleDate;
exampleDate = formatDateTime(useFormat);
private Date formatDateTime(String dateStr){
Date newDate = null;
DateFormat outdfm = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss");//"MM-dd-yy HH:mm:ss"//MMM dd hh:mm:ss yyyy
try{
newDate = outdfm.parse(dateStr);
}
catch (ParseException e){
e.printStackTrace();
}
return newDate;
}

Example 2:
Date curDate = new Date();
Calendar cal = Calendar.getInstance();
String dateStr = "2009-03-19T10:10:51";
curDate = formatDateTime(dateStr);
cal.setTime(curDate);
private static Date formatDateTime(String dateStr){
Date newDate = null;
//DateFormat outdfm = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss");//"MM-dd-yy HH:mm:ss"//MMM dd hh:mm:ss yyyy
DateFormat outdfm = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss");// 2009-03-19T10:10:51//"yyyy.MM.dd G 'at' hh:mm:ss z"->> 1996.07.10 AD at 15:08:56 PDT
try{
newDate = outdfm.parse(dateStr);
}catch (ParseException e){
e.printStackTrace();
}
return newDate;
}


Thanks for reading, and Thanks for stopping by!!

~Nirmal

Today is the Tomorrow we worried about yesterday
~from somebody's email signature