Sample class contains methods that parses Date object to different formats. This class can be used as utility class in converting Date object to String or Calendar.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
public class MyDateUtility
{
private final static Logger LOGGER = Logger.getLogger(MyDateUtility.class .getName());
/**
* Parses the date from YYMMDD to yyyy-MM-dd+HH:mm format.
* @param date - cyymmdd
* @return
*/
public static String formatDate1(String date)
{
Date d1 = null;
SimpleDateFormat df=new SimpleDateFormat("yyMMdd");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd+HH:mm");
Calendar cal = new GregorianCalendar();
try
{
d1 = df.parse(date);
} catch (ParseException e)
{
e.printStackTrace();
}
cal.setTime(d1);
return output.format(d1);
}//end method
/**
* Return String Date based on the toFormat parameter.
*/
public static String formatDate(String date, String currentFormat, String toFormat)
{
Date d1 = null;
SimpleDateFormat df=new SimpleDateFormat(currentFormat);
SimpleDateFormat output = new SimpleDateFormat(toFormat);
Calendar cal = new GregorianCalendar();
try
{
d1 = df.parse(date);
} catch (ParseException e)
{
e.printStackTrace();
}
cal.setTime(d1);
return output.format(d1);
}//end method
/**
* Return Date in Calendar format.
*/
public static Calendar getCalendarObject(String date, String format)
{
Calendar cal = new GregorianCalendar();
SimpleDateFormat output = new SimpleDateFormat(format);
try
{
cal.setTime(output.parse(date));
} catch (ParseException e)
{
e.printStackTrace();
}
return cal;
}//end method
/**
* Format Calendar object to string based on the passed format.
* @param cal
* @param format - e.g. yyyy-MM-dd+HH:mm
* @return
*/
public static String calendarToStringFormat(Calendar cal, String format)
{
SimpleDateFormat output = new SimpleDateFormat(format);
return output.format(cal.getTime());
}//end method
}//end class
No comments:
Post a Comment