On the leap year, [NSDate date] returns 2012-03-01 HH:MM:SS +TTTT.
On stackoverflow I’ve often seen posts where today’s date is retrieved by simply calling [NSDate date]. The problem is that on the leap year this is not going to return the correct date. Now I understand that the leap year is actually a function of a calendrical system so it makes sense that NSDate wouldn’t recognize the leap year (or daylight savings time for that matter). However, this has the potential to wreck havoc in code – for example:
say you assign a file modification date by doing:
// assume today's date is 2012-02-29 10:00:00 +0000
NSDate *fileModificationDate = [NSDate date]; // 2012-03-01 10:00:00 +0000 is returned
Then at some point in the future you do a comparison to see when the file was last modified:
// assume it's the next day at 9 AM, ie 2012-03-01 09:00 +0000
NSTimeInterval timeSinceLastModification = [fileModificationDate timeIntervalSinceNow];
The returned timeSinceLasModification will be positive, signifying a time in the future which makes no sense!
My questions is: is it actually bad practice to use [NSDate date] to get the current date? Am I missing something important here?
Sorry for the long winded question…
I don’t know where you got the idea that
NSDatedoesn’t support leap day, but it’s absolutely wrong. I believe you’re getting confused because right now in GMT, the date string is2012-03-01 03:42:07 +0000. This is correct. In GMT, it’s already March 1st. But if you ask for the date in the current locale (e.g.[[NSDate date] descriptionWithLocale:[NSLocale currentLocale]]) you’ll get a correct value of leap day. For me in PST, it’sNote that
NSDateitself is locale-unaware. The only change I made was asking it to return the string representation using the current locale instead of using GMT. I could take that same date object and ask for EST and it would give me the correct string for that time zone as well.