Home  >  Article  >  Java  >  Why Is SimpleDateFormat Incorrectly Displaying Months When Converting Dates?

Why Is SimpleDateFormat Incorrectly Displaying Months When Converting Dates?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 08:04:02409browse

Why Is SimpleDateFormat Incorrectly Displaying Months When Converting Dates?

Java SimpleDateFormat Misrepresenting Months

When converting dates from Active Directory to Java, the SimpleDateFormat is consistently displaying all dates in January, despite correctly identifying days and years. Investigating the code provided, the issue lies in the formatting pattern:

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

The pattern string "yyyy/MM/DD" signifies a format of year/month/day. However, the date value from Active Directory is formatted as year/month/day, with the day not capitalized. To rectify this, the pattern should be modified to:

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

By using a lowercase "d" for day instead of "DD," the date will be correctly parsed from the Active Directory data. The updated code would look like:

<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>

With this adjustment, the month will now be accurately extracted from the Active Directory date string.

The above is the detailed content of Why Is SimpleDateFormat Incorrectly Displaying Months When Converting Dates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn