首页 > 解决方案 > Java - DateFormat 在转换日期时不起作用

问题描述

我是 Java 新手。我一直在尝试将日期转换为dd-MMM-yy格式。但我得到了例外:

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date

下面是我的代码。请指导。

public class Test {
 public static void main(String args[ ])  {

     String currentDateString =new String();
     DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
     DateFormat dateFormatpdfname = new SimpleDateFormat("dd-MMM-yy");
        //Date currentDate = new Date();
       String dateInString = "Sep 16, 2018";
       String dateInString1 = "16-Sep-18";
        String currentDateVal=dateFormatpdfname.format(dateInString1);
        currentDateString = dateFormat.format(dateInString);
        System.out.println(currentDateVal);
        System.out.println(currentDateString);
}
}

标签: javasimpledateformatdate-format

解决方案


Uncomment this 
//Date currentDate = new Date();
Then,
String currentDateVal=dateFormatpdfname.format(currentDate );
        currentDateString = dateFormat.format(currentDate );

推荐阅读