Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date string conversion to standard format 1

Status
Not open for further replies.

ddj26

Technical User
Jul 13, 2001
6
GB
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;
}

public static String convertDateToString(Date date, String format)
{
String retDateString=null;
if(date!=null)
{

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);
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top