且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不可稀释的日期:转换日期从dd MMM yyyy格式到dd / MM / yyyy

更新时间:2023-02-26 20:08:02

假设你修正了公然的语法错误,然后:

  String dateStr =2014年12月16日//< ==这个日期是dd MMM yyyy 
formatter = new SimpleDateFormat(dd / MM / yyyy); //< ==这个SDF是在dd / MM / yyyy
Date thedate = formatter.parse(dateStr); //< ==那么怎么可以预期解析?

您所做的是为您需要解析的格式创建一个解析器,并为格式化格式化程序你想要:

  String dateStr =2014年12月16日; 
SimpleDateFormat parser = new SimpleDateFormat(dd MMM yyyy);
日期thedate = parser.parse(dateStr);
SimpleDateFormat formatter = new SimpleDateFormat(dd / MM / yyyy);
String dateStrReformatted = formatter.format(thedate);


I get Unparseable error when I run below code. How can I convert dd MMM yyyy format to dd/MM/yyyy format?

public Calendar myMethod(){
   String dateStr = "16 Dec 2014"
   SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
   Date thedate = formatter.parse(dateStr);

   Calendar cal = Calendar.getInstance();
   cal.setTime(thedate);
   return cal;
}

Assuming you fix the blatant syntax errors, then:

String dateStr = "16 Dec 2014"                // <== This date is in dd MMM yyyy
formatter = new SimpleDateFormat(dd/MM/yyyy); // <== This SDF is in dd/MM/yyyy
Date thedate = formatter.parse(dateStr);      // <== So how can it be expected to parse?

What you do is create a parser for the format you need to parse, and a formatter for the format you want:

String dateStr = "16 Dec 2014";
SimpleDateFormat parser = new SimpleDateFormat("dd MMM yyyy");
Date thedate = parser.parse(dateStr);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateStrReformatted = formatter.format(thedate);