How can I convert a date string in possible multi-formats (eg 28/8/2001 08:10:01 AM & 28/8/2001 16:00:00 etc) to a fixed format (eg 28/08/2001 20:00:10). This would be in Java 2.
You could probably use the SimpleDateFormat class in java.text. Here is some of my code I used for a similar problem. It consists of one method which converts a String representing a date to a Date, and another which goes in the opposite direction. There is also a small method incorporating both of these that converts a String to a String with a different format. These methods take in the date to be converted, and the format from which it is to be converted (in the case of convertToDate) or to which it is to be converted (in the case of convertDateToString). In your case, you could probably initially try to convert from the first of your two possible formats; if this throws an exception, then try the second format. See the SimpleDateFormat API for more info. Hope this helps.
public static Date convertToDate(String sDate, String formatType)
{
Date date = null;
if (sDate!=null&&!sDate.trim().equals("")
{
SimpleDateFormat dateFormat = new SimpleDateFormat(formatType);
ParsePosition pos = new ParsePosition(0);
date = dateFormat.parse(sDate, pos);
}
return date;
}
SimpleDateFormat retDate = new SimpleDateFormat(format);
retDateString=retDate.format(date);
}
return retDateString;
}
//following method is a combination of the above 2
public static String convertDateString(String currentFormat, String newFormat, String currentDateString)
{
//this class is called UtilFormat!!!
Date date = UtilFormat.convertToDate(currentDateString, currentFormat);
return UtilFormat.convertDateToString(date, newFormat);
}
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.