Search code examples
iosswiftnsdateformatter

iOS Date() returns incorrect value


I am using the below code to get the iOS device date.

    let today = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd"
    let currentDate = dateFormatter.string(from: today)
    print("todayDate : \(currentDate)")
    dateFormatter.dateFormat = "MM"
    let currentMonth = dateFormatter.string(from: today)
    print("currentMonth : \(currentMonth)")
    dateFormatter.dateFormat = "YYYY"
    let currentYear = dateFormatter.string(from: today)
    print("currentYear : \(currentYear)")

When I am changing device date in iPhone setting 29-12-2019 or 30-12-2019 or 31-12-2019. currentMonth and currentDate values are correct. but, the currentYear return value is 2020 instead of 2019. Kindly suggest me to solve this issue.


Solution

  • A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year. see this for help : Challenges of DateFormatters

    use your dateformat

    "yyyy" is ordinary calendar year.

    dateFormatter.dateFormat = "yyyy"
    

    instead of

    "YYYY" is week-based calendar year.

    dateFormatter.dateFormat = "YYYY"
    

    finally as per your question ,

       let today = Date()
       let dateFormatter = DateFormatter()     
       dateFormatter.dateFormat = "yyyy"
       let currentYear = dateFormatter.string(from: today)
       print("currentYear : \(currentYear)")
    

    you get the output as

    enter image description here