2016-01-06 116 views
1

我有以下代码创建LocalDate。当我调用它的toString方法时,输出是2016-01-05。joda格式化LocalDate

我希望日期采用以下格式。 05-Jan-2016

int dayInt = Integer.parseInt(dayStr); 
      int monthInt = Integer.parseInt(monthStr); 
      int yearInt = Integer.parseInt(yearStr); 

      LocalDate ldt = new LocalDate(yearInt, monthInt, dayInt); 

      Log.e(TAG, "LocalDate = " + ldt.toString()); //eg 2016-01-05 


      LocalDate localDate2 = LocalDate.parse(ldt.toString(), DateTimeFormat.forPattern("dd-MMM-yy")); 

我得到以下异常,有谁知道我该怎么做?

在此先感谢。

01-06 14:34:13.903: E/CustomExceptionHandler(8590): stack = java.lang.IllegalArgumentException: Invalid format: "2016-01-04" is malformed at "16-01-04" 
01-06 14:34:13.903: E/CustomExceptionHandler(8590):  at org.joda.time.format.DateTimeFormatter.parseLocalDateTime(DateTimeFormatter.java:821) 
01-06 14:34:13.903: E/CustomExceptionHandler(8590):  at org.joda.time.format.DateTimeFormatter.parseLocalDate(DateTimeFormatter.java:765) 
01-06 14:34:13.903: E/CustomExceptionHandler(8590):  at org.joda.time.LocalDate.parse(LocalDate.java:178) 

回答

1

表达ldt.toString()产生 “2016年1月5日”。

所以你的格式模式应该是:“yyyy-MM-dd”,但是你开始你的模式,期待只有两位数字(如错误信息所示)。

你说:

我想日期为按以下格式。 05-JAN-2016

然后,你必须将其格式化(不解析它):

String s = DateTimeFormat.forPattern("dd-MMM-yyyy").withLocale(Locale.ENGLISH).print(ldt); 
0

年份的格式不正确。改变线:

LocalDate localDate2 = LocalDate.parse(ldt.toString(), DateTimeFormat.forPattern("dd-MMM-yy")); 

到:

LocalDate localDate2 = LocalDate.parse(ldt.toString(), DateTimeFormat.forPattern("dd-MMM-yyyy")); 
+0

嗨,不,我仍然得到同样的错误,我很害怕 – turtleboy