【问题标题】:Java date format convert yy to yyyy issueJava日期格式将yy转换为yyyy问题
【发布时间】:2017-04-04 10:11:31
【问题描述】:

Java 日期格式问题,当我尝试使用以下代码转换日期 04-Apr-17 时:

       DateFormat informat= new SimpleDateFormat("dd-MMM-yy");
       DateFormat outformat= new SimpleDateFormat("dd-MMM-yyyy");
       System.out.println(outformat.format(informat.parse("04-Apr-17")));

我得到的是 0017 年 4 月 4 日而不是 2017 年 4 月 4 日。

我尝试了很多方法,但没有任何好的解决方案。

请帮忙,谢谢!

【问题讨论】:

  • 对我来说效果很好
  • 我也无法重现您观察到的行为。您的计算机(或者更确切地说是 JVM)的默认语言环境是什么?对于04-Apr-7,我得到04-Apr-0007 好吧,但是17 变成了2017。
  • 由于 Giovanni Montenegro 尚未获得足够的评论声誉,here is the link to his demonstration that the code works fine
  • 在任何情况下,您所做的事情都是危险的,除非您非常确定要转换到过去或未来多远的日期。假设您将05-Apr-37 转换为05-Apr-1937,测试并确保一切正常。当你下周运行相同的程序时,它会转换为05-Apr-2037,一个巨大的错误。
  • 了解该 PC 上的当前日期/时间以及 PC 的区域设置会很有趣:或者当您提供专用区域设置时也会发生这种情况:例如美国到 SimpleDateFormat ()

标签: java date simpledateformat


【解决方案1】:

我知道了这个问题的原因,我在 JSF 环境中使用了这个日期转换,并且正在检查用户从网页输入的日期模式。 当用户传递“dd-MMM-yy”模式时,我有下面的代码来解析一些支持的日期模式列表的日期。

    Date date = null;
    boolean isDateValid = false;
    for (String pattern : patterns) {

        DateFormat df = new SimpleDateFormat(pattern);
        try {
            date = df.parse(value);

            String newDateString = df.format(date);
            System.out.println(newDateString);

            isDateValid = true;
            break;

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    System.out.println("Date : " + date);

因此,当用户以“dd-MMM-yy”模式提供日期时,但“dd-MMM-yy”模式也被以下代码中的“dd-MMM-yyyy”模式解析:

    DateFormat df = new SimpleDateFormat(pattern);
    date = df.parse(value);

这就是原因,我得到的是 04-Apr-0017 而不是 04-Apr-2017。

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2012-03-05
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多