Java-转换日期时DateFormat不起作用

时间:2018-09-19 10:43:19

标签: java simpledateformat date-format

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

2 个答案:

答案 0 :(得分:0)

可能我没有将其作为日期传递,这就是我出错的原因。下面是正确的答案。

 public class Test {
     public static void main(String args[ ]) throws ParseException  {
          //Base obj1 = new Base();
     // As per overriding rules this should call to class Derive's static 
     // overridden method. Since static method can not be overridden, it 
     // calls Base's display() 
          //Derived.display(); 
         Date myDate = null;
         String currentDateString =new String();
         DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
       //  DateFormat dateFormatpdfname = new SimpleDateFormat("dd-MMM-yy");
            //Date currentDate = new Date();
          // String dateInString = "Sep 16, 2018";
           String dateInString1 = "16-Sep-18";
           myDate = dateFormat.parse(dateInString1);
            //String currentDateVal=dateFormatpdfname.format(dateInString1);
            currentDateString = dateFormat.format(myDate);
            //String releaseDateStr = dateFormat.format(currentDateString);
        //  System.out.println(currentDateVal);
            System.out.println(currentDateString);
    }
    }

答案 1 :(得分:0)

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