1

我下面的代码有什么问题?

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

2 回答 2

2

没有。这在我的电脑上工作得很好。

编辑:那没有帮助。您可能需要考虑特定的区域设置。如果您的语言环境需要不同的月份名称/日期名称,您将得到一个例外。

编辑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();
    }
于 2011-06-02T23:29:56.390 回答
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);
}
于 2011-06-03T00:02:36.140 回答