Search code examples
iosswiftnsdatensdateformatternsdatecomponents

NSDate returning wrong date in Swift


Today is Feb 1 of 2016 and I just opened up my working app to continue my work and this shocks me.

Image

It is a collection view of date, I didn't notice anything wrong during January because it hasn't been a month.

Here's the code,

func dF(someDate:NSDate) -> (String){
let monthFormat = NSDateFormatter()
let dayFormat = NSDateFormatter()
monthFormat.dateFormat = "MMM"
dayFormat.dateFormat = "D"

let aMonth = monthFormat.stringFromDate(someDate)
let aDay = dayFormat.stringFromDate(someDate)

//concatenate strings
let conString = aMonth + " " + aDay

return (conString)
}


//from today to 7th day, to be used in ScrollView
let day1 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: 0, toDate: NSDate(), options: [])
let day2 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -1, toDate: NSDate(), options: [])
let day3 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -2, toDate: NSDate(), options: [])
let day4 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -3, toDate: NSDate(), options: [])
let day5 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -4, toDate: NSDate(), options: [])
let day6 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -5, toDate: NSDate(), options: [])
let day7 = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -6, toDate: NSDate(), options: [])
let titles = [dF(day1!), dF(day2!), dF(day3!), dF(day4!), dF(day5!), dF(day6!), dF(day7!)]

I'm expecting day1 to pass the current date to function dF and format it.

So I ran some checks to make sure I've got the correct date Current time: Feb 1, 2016, 1:08am in my time zone

print(day1)
print(day2)
print(ddd)

Here's the result from console:

Optional(2016-01-31 17:08:47 +0000)

Optional(2016-01-30 17:08:47 +0000)

Feb 32

I'm suspecting my NSDateComponent isn't setup correctly/on par with local time zone. Any ideas?


Solution

    1. You are using the wrong specifier for the day of the month.
    2. You are creating your date string the hardest way possible.

    Try this:

    Swift 3/4:

    func dF(_ someDate: Date) -> String {
        let format = DateFormatter()
        format.dateFormat = "MMM d"
        // For a more localized format, use the following instead:
        // format.setLocalizedDateFormatFromTemplate("MMMd")        
    
        let conString = format.string(from: someDate)
    
        return conString
    }
    

    Old Swift 2 answer: func dF(someDate:NSDate) -> (String){ let format = NSDateFormatter() format.dateFormat = "MMM d"

        let conString = format.stringFromDate(someDate)
    
        return (conString)
    }