【问题标题】:Convert date time value to expected with SimpleDateFormat使用 SimpleDateFormat 将日期时间值转换为预期值
【发布时间】:2012-11-12 10:26:43
【问题描述】:

我在使用 SimpleDateFormat (java) 将日期时间值转换为预期值时遇到问题,我的预期格式是 MM/yyyy,我想将 2 个值仅转换为 1 种格式

  1. MM-yyyy 例如 05-2012
  2. yyyy-MM 例如 2012-05

输出为 05/2012。

我实现了如下所示的东西

String expiry = "2012-01";
try {
    result = convertDateFormat(expiry, "MM-yyyy", expectedFormat);
} catch (ParseException e) {
    try {
        result = convertDateFormat(expiry, "yyyy-MM", expectedFormat);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    e.printStackTrace();
}

private String convertDateFormat(String date, String oPattern, String ePattern) throws ParseException {
    SimpleDateFormat normalFormat = new SimpleDateFormat(oPattern);
    Date d = normalFormat.parse(date);
    SimpleDateFormat cardFormat = new SimpleDateFormat(ePattern);
    return cardFormat.format(d);
}

现在,返回值为6808,不知道为什么。

请任何人帮助我处理此案。

【问题讨论】:

  • 如果解析2012-05,真的会尝试第二种方式吗?还是从第一种格式解析并得到错误的结果?您可以在选择格式方法之前在“-”位置设置条件。
  • 请接受答案,到目前为止您还没有接受任何答案。
  • 我同意@Quoi 你根本不接受任何答案。
  • @AlexandreLavoie:如果我将 2012-01 更改为 2012-05,则输出为 7208 而不是

标签: java simpledateformat dataformat


【解决方案1】:

SimpleDateFormat#setLenient() 添加到您的convertDateFormat 方法中:

private String convertDateFormat(String date, String oPattern, String ePattern) throws ParseException {
    SimpleDateFormat normalFormat = new SimpleDateFormat(oPattern);
    normalFormat.setLenient(false); /* <-- Add this line -- */
    Date d = normalFormat.parse(date);
    SimpleDateFormat cardFormat = new SimpleDateFormat(ePattern);
    return cardFormat.format(d);
}

如果日期不正确,它会使convertDateFormat 失败。

这里有详细解释:http://eyalsch.wordpress.com/2009/05/29/sdf/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2022-01-06
    • 2013-08-29
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多