我有一个简单的任务,就是将格式为“ 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句