【问题标题】:SimpleDateFormat parse and format on same date string gives different resultsSimpleDateFormat 解析和格式化相同的日期字符串给出不同的结果
【发布时间】:2014-09-15 12:15:47
【问题描述】:

我有一个简单的任务,即将这种格式的日期:“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。哇。

【问题讨论】:

    标签: java android simpledateformat


    【解决方案1】:

    您在第一种格式中使用了大 D:

         new SimpleDateFormat("yyyy-MM-DD", Locale.ENGLISH);
    

    但 D 代表一年中的一天。你必须使用dd,这是一个月中的一天。将其更改为:

         new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
    

    【讨论】:

    • 天哪,你是对的。其实代码不是我的,我在调试别人的。我应该责怪这家伙哈哈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2022-11-07
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多