【问题标题】:Error converting custom date format to another using SimpleDateFormat使用 SimpleDateFormat 将自定义日期格式转换为另一种时出错
【发布时间】:2011-06-02 23:26:03
【问题描述】:
我下面的代码有什么问题?
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.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);
}
【问题讨论】:
标签:
java
date
date-format
simpledateformat
【解决方案1】:
什么都没有。这在我的电脑上运行良好。
编辑:这没有帮助。您可能需要考虑特定的区域设置。如果您的语言环境需要不同的月份名称/日期名称,您将得到一个例外。
编辑 2:试试这个:
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();
}
【解决方案2】:
这应该可行:
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);
}