2016-01-06 46 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