首页  >  文章  >  Java  >  为什么 SimpleDateFormat 在转换日期时无法正确显示月份?

为什么 SimpleDateFormat 在转换日期时无法正确显示月份?

Patricia Arquette
Patricia Arquette原创
2024-10-24 08:04:02409浏览

Why Is SimpleDateFormat Incorrectly Displaying Months When Converting Dates?

Java SimpleDateFormat 错误表示月份

将日期从 Active Directory 转换为 Java 时,SimpleDateFormat 始终显示 1 月份的所有日期,尽管正确识别几天和几年。研究提供的代码,问题在于格式模式:

<code class="java">SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/DD");</code>

模式字符串“yyyy/MM/DD”表示年/月/日的格式。但是,Active Directory 中的日期值的格式为年/月/日,其中日不大写。要纠正此问题,应将模式修改为:

<code class="java">SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");</code>

通过使用小写“d”代替“DD”来表示日期,将从 Active Directory 数据中正确解析日期。更新后的代码如下所示:

<code class="java">private Date getParsedDate(String givenString) {
    System.out.println("Value from AD is: " + givenString);
    Date parsedDate = null;
    String formattedString = this.formatDateString(givenString);
    System.out.println("Formatted String is: " + formattedString);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    try {
        parsedDate = sdf.parse(formattedString);
        System.out.println("Final date string is: " + parsedDate.toString());
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
    return parsedDate;
}</code>

通过此调整,现在将从 Active Directory 日期字符串中准确提取月份。

以上是为什么 SimpleDateFormat 在转换日期时无法正确显示月份?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn