使用SimpleDateFormat将自定义日期格式转换为另一种格式时出错

时间:2011-06-02 23:26:03

标签: java date date-format simpledateformat

我的代码在下面出了什么问题?

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

2 个答案:

答案 0 :(得分:2)

无。这在我的电脑上运行得很好。

编辑:那没用。您可能需要考虑特定的区域设置。如果您的Locale需要不同的月份名称/日期名称,您将获得例外。

编辑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();
    }

答案 1 :(得分: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);
}