Home > Java > javaTutorial > body text

Why Is SimpleDateFormat Incorrectly Displaying Months When Converting Dates?

Patricia Arquette
Release: 2024-10-24 08:04:02
Original
418 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!