我有一个简单的任务,即将以下格式的日期:“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 解析为日期对象。然后,我使用完全相同的输入日期格式格式化结果字符串,然后日期被更改。就好像你解析了字符串“1”,然后它变成了整数2,然后当你把整数变回字符串时它变成了3。什么。
最佳答案
您在第一种格式中使用了大 D:
new SimpleDateFormat("yyyy-MM-DD", Locale.ENGLISH);
但 D 代表一年中的一天。您必须使用 dd,即一个月中的某一天。将其更改为:
new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
关于java - SimpleDateFormat 对同一日期字符串的解析和格式化给出了不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25847903/