首頁  >  文章  >  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