I am new to Java. I have been trying to convert a date into format dd-MMM-yy. But i am getting exception :
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
Below is my code . Please guide.
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);
}
}
Stringto theformatmethod while it expects aDateobject.SimpleDateFormatclass. It is not only long outdated, it is also notoriously troublesome. Today we have so much better injava.time, the modern Java date and time API.SimpleDateFormatclass too. This is not recommended. Use for example the Parsing and Formatting section of the Oracle tutorial instead.