Search code examples
iosswift2nsdatenscalendarios9.2

How to make adding days to NSCalendar work in all Timezones/Regions


I have the following block of code in Swift 2.0 that I'm using to add 3 days from the current date to retrieve the weather data for that specific day.

var inThreeDaysValue: String {
    let newDate = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: 3,
        toDate: currentDate, options: NSCalendarOptions.init(rawValue: 0))

    dateFormatter.dateFormat = "YYYY-MM-dd"

    print("*** IN THREE DAYS \(dateFormatter.stringFromDate(newDate!))")
    return "\(dateFormatter.stringFromDate(newDate!)) 12:00:00"

}

The fact is that if I run this code in my simulator (using "United States" as region) the new date will be set to 3 days and 1 year ahead (if today it's the 2015-12-24 the new date will be 2016-12-27).

On the contrary, if I set my emulator's region to "United Kingdom" or "Italy" the code performs perfectly and the new date is the exact one.

I'm wondering why this happens and if there is a way to make this code working in all timezone and regions provided by iOS 9.2


Solution

  • Change the YYYY to lowercase as the following:

    dateFormatter.dateFormat = "yyyy-MM-dd"
    

    The description for this problem would be:

    One major thing to note, there is a difference between “yyyy” and “YYYY”. In most cases, you probably want to use the lowercase one, “yyyy”. The uppercase one is the “Week of Year” style of year.

    You can read all about it in here: http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/

    Good luck :)