2016-07-11 36 views
0

我有一個變量:從YearMonth(YYYY-MM)到YearMonth(YYYY-MMMM)

YearMonth date; 

其中內部站在"2016-07",例如。

我希望它仍然是YearMonth,但是"2016 july"(注意,沒有「 - 」分隔符),或者甚至更好,即意大利語語言環境"2016 luglio"

怎麼辦?

UPDATE

我試着用JackDaniels的方法。它實際上可以工作,因爲它給了我一個字符串(str)和正確的日期格式。但我需要再次將該字符串放入我的YearMonth變量中。我試着用:

myVariable = YearMonth.parse(str); 

但它返回我一個錯誤:java.time.format.DateTimeParseException: Text '2014 gennaio' could not be parsed at index 4

如何解決這個問題?

+0

你試過更新的代碼嗎?它有解析的例子,然後格式化日期是兩個不同的時區。嘗試編輯代碼,並向我們展示您嘗試的內容,這樣我們可以提供更好的幫助。 – JackDaniels

回答

2

使用新的DateTimeFormatter直接解析和格式化YearMonth並使用Locale來設置所需的語言環境。 不要使用SimpleDateFormat。這是舊的Date API的一部分。

嘗試運行代碼,看看這是否是你想要的Codiva online compiler IDE

YearMonth yearMonth = YearMonth.of(2016, 7); 
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MMMM", 
    new Locale("it", "IT")); 
System.out.println(yearMonth.format(formatter)); 

完整的工作代碼在Codiva

+0

yearMonth.format(formatter)會給我一個字符串。我試圖做 myVariable = YearMonth.parse(str),但它會給我一個錯誤: java.time.format.DateTimeParseException:無法在索引4處解析文本'2014 gennaio' – Marco

+0

使用此方法。 https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter- 更新瞭解析示例代碼在Codiva鏈接。 – JackDaniels

+0

無法正常工作。你可以看到自己回報「2014-01」,而不是「2014年1月」 – Marco

相關問題