Error converting custom date format to another using SimpleDateFormat
What's wrong with my code below?
try {
// dataFormatOrigin (Wed Jun 01 14:12:42 2011)
// this is original string with the date information
SimpleDateFormat sdfSource = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
Date date = sdfSource.parse(dataFormatOrigin);
// (01/06/2011 14:12:42) - the destination format that I want to have
SimpleDateFormat sdfDestination = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
dataFormatDest = sdfDestination.format(date);
System.out.print开发者_如何学运维ln("Date is converted to MM-dd-yyyy hh:mm:ss");
System.out.println("Converted date is : " + dataFormatDest);
} catch (ParseException pe) {
System.out.println("Parse Exception : " + pe);
}
Nothing. This works just fine on my computer.
EDIT: that wasn't helpful. You may have specific Locale settings that need to be considered. If your Locale expects different month names/day names you will get an exception.
EDIT 2: Try this:
try{
String dataFormatOrigin = "Wed Jun 01 14:12:42 2011";
// this is original string with the date information
SimpleDateFormat sdfSource = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.US);
Date date = sdfSource.parse(dataFormatOrigin);
// (01/06/2011 14:12:42) - the destination format that I want to have
SimpleDateFormat sdfDestination = new SimpleDateFormat( "dd-MM-yyyy hh:mm:ss");
String dataFormatDest = sdfDestination.format(date);
System.out .println("Date is converted to MM-dd-yyyy hh:mm:ss"); System.out .println("Converted date is : " + dataFormatDest);
} catch (ParseException pe) {
System.out.println("Parse Exception : " + pe);
pe.printStackTrace();
}
This should work:
try {
// dataFormatOrigin (Wed Jun 01 14:12:42 2011)
// this is original string with the date information
// (01/06/2011 14:12:42) - the destination format
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MM-yyyy hh:mm:ss");
sdfDestination.setLenient( true );
// ^ Makes it not care about the format when parsing
Date date = sdfDestination.parse(dataFormatOrigin);
dataFormatDest = sdfDestination.format(date);
System.out
.println("Date is converted to MM-dd-yyyy hh:mm:ss");
System.out
.println("Converted date is : " + dataFormatDest);
} catch (ParseException pe) {
System.out.println("Parse Exception : " + pe);
}
精彩评论