2014-06-23 48 views
0

我在Java中使用其他格式轉換日期時遇到了問題(我正在使用Joda-Time)。其實,我有一個格式化本地日期是:在Joda-Time上將mediumDate()轉換爲其他格式(使用Locale)

24/giu/14 (Italian format date...but other local formats are possible) 

我想看到這個輸出(使用區域設置格式日期):

24/06/2014 

我試圖建立一個示例代碼,但不起作用......我做錯了什麼?

public String DateConvertFromMediumFormatToSlash (String date) 
    { 
     DateTimeFormatter dtf = DateTimeFormat.mediumDate().withLocale(Locale.getDefault()); 
     LocalDate dt = dtf.parseLocalDate(date); 

     return dt.toString(); // output: 2014-06-24 
    } 
+1

你的問題很混亂。您的輸入究竟是什麼?你想要什麼作爲你的輸出? –

回答

3

你的問題是關於你作爲輸入和你想要輸出什麼的混淆。

意大利使用連字符,不斜線

但有一個問題似乎是斜線。喬達時代預計連字符不會縮減。以下是使用Joda-Time 2.3的一些示例代碼,使用意大利語語言環境的中等格式向您顯示LocalDate看起來像一個字符串。

LocalDate localDate = new LocalDate(2014, 6, 24); 
System.out.println("localDate: " + localDate); 

DateTimeFormatter formatter = DateTimeFormat.mediumDate().withLocale(Locale.ITALY); 
System.out.println("output: " + formatter.print(localDate)); 

運行時...

localDate: 2014-06-24 
output: 24-giu-2014 

定義格式化爲斜線

所以,如果你想解析/生成用斜槓,而不是預計意大利的語言環境,必須在連字符的字符串明確定義這樣一個格式化程序。

String input = "24/giu/14"; 
DateTimeFormatter formatterInput = DateTimeFormat.forPattern("dd/MMM/yy").withLocale(Locale.ITALY); 
LocalDate localDate = formatterInput.parseLocalDate(input); 
System.out.println("localDate: " + localDate); 

DateTimeFormatter formatterOutput = DateTimeFormat.forPattern("dd/MM/yy").withLocale(Locale.ITALY); // Locale not needed here, but it's a good habit to specify. 
String output = formatterOutput.print(localDate); 
System.out.println("Output: " + output); 

當運行...

localDate: 2014-06-24 
Output: 24/06/14 

順便說一句,用兩個數字表示年份是自討苦吃恕我直言。

+0

好的!謝啦! :) 你是對的!但是,我不明白一件事:我如何設置基於Locale的輸出模式?例如,意大利語的日期是dd/MM/yy ...但是,例如,英語模式不一樣......根據您的解決方案,我該如何管理這個問題?謝謝!! :) – user3449772

+0

@ user3449772你似乎忽略了我的整個答案。意大利的日期是* not *'dd/MM/yy'。我的第三行代碼顯示瞭如何獲取特定語言環境的格式。 –

+0

是的,對不起!因爲我目前正在從智能手機上閱讀而丟失了一篇文章!我認爲這對我來說是最好的解決方案!謝啦!我爲我的誤會道歉... :) – user3449772

相關問題