将Date从一种格式转换为另一种格式时出错

时间:2014-12-18 11:07:03

标签: java date

在以下代码中遇到问题。输出为dateStr: 11-Jan-11。谁能告诉我为什么修改日期?

String dateStr="";
String actionCompletionDueDate = "16/11/2011";
DateFormat srcDf = new SimpleDateFormat("mm/dd/yyyy");
DateFormat destDf = new SimpleDateFormat("dd-MMM-yy");              
if(actionCompletionDueDate != null && !actionCompletionDueDate.equals("")) {
  // parse the date string into Date object
  System.out.println("actionCompletionDueDate: " + actionCompletionDueDate);
  Date actionCompletionDate = srcDf.parse(actionCompletionDueDate);
  dateStr = destDf.format(actionCompletionDate);
  System.out.println("dateStr: " + dateStr);
}

3 个答案:

答案 0 :(得分:3)

更改

DateFormat srcDf = new SimpleDateFormat("mm/dd/yyyy"); 

DateFormat srcDf = new SimpleDateFormat("dd/MM/yyyy");

或者将正确的字符串(符合您的格式)传递给您的代码

String actionCompletionDueDate = "11/16/2011"; 

并将格式更正为DateFormat srcDf = new SimpleDateFormat("MM/dd/yyyy");

mm是几分钟而MM是几个月

答案 1 :(得分:1)

String actionCompletionDueDate = "16/11/2011";

应该是

String actionCompletionDueDate = "11/16/2011";

答案 2 :(得分:1)

更改

DateFormat srcDf = new SimpleDateFormat("mm/dd/yyyy");

DateFormat srcDf = new SimpleDateFormat("MM/dd/yyyy");

mm对应分钟

但如果您使用

打印源日期
System.out.println(actionCompletionDate.toString());

输出是:

Sun Jan 16 00:11:00 IST 2011

及时查看 11分钟

并将源日期也更改为11/16/2011