简体   繁体   中英

change date format DD-MON-YYYY to DD/MM/YYYY

I want to change date format which I received reading from excel cell file is "30-mar-2016" to 03/30/2016. I have tried below

     String inputDate = "30-mar-2016";
     DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
     Date startDate;
     startDate = df.parse(inputDate);

It gave me- java.text.ParseException: Unparseable date: "30-mar-2016" . I also tried below code

     String inputDate = "30-mar-2016";
     DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
     String startDate;
     startDate = df.format(inputDate);

getting -- java.lang.IllegalArgumentException: Cannot format given Object as a Date

Can anyone help me .

Your input string 30-mar-2016 is in the format dd-MMM-yyyy . Your output format is MM/dd/yyyy . So you need two DateForamt s. One for parsing original input string, one for formatting output string.

DateFormat df1 = new SimpleDateFormat("dd-MMM-yyyy"); // for parsing input
DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");  // for formatting output
String inputDate = "30-mar-2016";
Date d = df1.parse(inputDate);
String outputDate = df2.format(d); // => "03/30/2016"

I have resolved using below

     SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
     Date date = sdf.parse("30-mar-2016");
     sdf.applyPattern("MM/dd/yyyy");
     System.out.println(sdf.format(date));//got 03/30/2016

Thanks everyone for your quick response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM