[英]SimpleDateFormat parse and format on same date string gives different results
我有一個簡單的任務,就是將格式為“ 2014-06-13”的日期轉換為格式為“ 2013年1月6日”
我為此聲明了兩個SimpleDateFormat
對象:
private SimpleDateFormat mInputFormat = new SimpleDateFormat("yyyy-MM-DD", Locale.ENGLISH);
private SimpleDateFormat mOutputFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
因此,我編寫了代碼來做到這一點:
Log.v(TAG, "orig: " + releaseDate);
try {
Date date = mInputFormat.parse(releaseDate); // create a date object using the first pattern
Log.v(TAG, "parsed:" + mInputFormat.format(date));
String newDate = mOutputFormat.format(date); // format the date object into the new format
Log.v(TAG, newDate);
aq.id(R.id.text_2).text(newDate); // sets the date
} catch (ParseException e) {
e.printStackTrace();
}
事實是,日期已完全關閉。 這是記錄在日志上的內容:
09-15 20:07:49.035: V/TwoLinerListItemView(26700): orig: 2014-06-13
09-15 20:07:49.035: V/TwoLinerListItemView(26700): parsed:2014-01-13
09-15 20:07:49.035: V/TwoLinerListItemView(26700): January 13, 2014
我對為什么這些結果如此不同感到困惑。 首先,使用輸入格式將原始字符串2014-06-13解析為日期對象。 然后,我使用完全相同的inputdate格式對結果字符串進行了格式化,然后更改了日期。 就像您解析字符串“ 1”,然后將其變為整數2,然后將整數重新生成為字符串時,其變為3。
您在第一種格式中使用了大D:
new SimpleDateFormat("yyyy-MM-DD", Locale.ENGLISH);
但是D是一年中的一天。 您必須使用dd,即每月的天數。 更改為:
new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.