簡體   English   中英

將日期格式DD-MON-YYYY更改為DD / MM / YYYY

[英]change date format DD-MON-YYYY to DD/MM/YYYY

我想將我從excel單元文件中讀取的日期格式更改為2016年3月30日至2016年3月30日。 我在下面嘗試過

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

它給了我java.text.ParseException:無法解析的日期:“ 30-mar-2016”。 我也嘗試下面的代碼

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

獲取-java.lang.IllegalArgumentException:無法將給定對象格式化為日期

誰能幫我 。

您輸入的字符串30-mar-2016的格式為dd-MMM-yyyy 您的輸出格式為MM/dd/yyyy 因此,您需要兩個DateForamt 一種用於解析原始輸入字符串,一種用於格式化輸出字符串。

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"

我已經解決了使用下面

     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

謝謝大家的快速反應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM