Does [NSDate date] return the local date and time?

故事扮演 提交于 2019-11-27 15:15:53

NSDate returns the current date. Though it can convert to and from string format in different locales/time zones, NSDate has no internal concept of a time zone. NSDates are not bound to any particular region. If you and anyone else in the world asked your devices to [NSDate date] simultaneously, you'd get equal results — not because it always returns in GMT but because it doesn't return in a time zone-specific manner. In Cocoa, a date is a specific moment in the history of the Earth. How you write a date is related to your calendar, your time zone and your locale.

You aren't getting tomorrow's date, you're getting the correct date and then noticing it gives a different day if expressed in GMT. It's the correct date, just written differently from what you'd like.

'description' is a method overridden from NSObject. When you NSLog an object, what happens internally is that the description method is called and the string returned is printed. So you should get identical results from logging object and [object description], since the former calls description and prints that string, the latter calls description then calls description on the resulting string and prints that. NSStrings return themselves as the result of description.

It should be the default behaviour but to get a meaningful description, try:

NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:nil 
           timeZone:[NSTimeZone localTimeZone] locale:[NSLocale currentLocale]]);

If that still logs in GMT then your device believes itself to be in GMT. I've no idea how reliable the simulator is about that sort of thing.

In Swift:

NSDate() gives us an agnostic date's description, it always returns the UTC+0 date time, independently of the device's time zone:

print(NSDate())

.descriptionWithLocale(NSLocale.currentLocale())! gives us a localized date's description UTC+N date time where N represents the offset (positive or negative) between UTC+0 and the current local date time:

print(NSDate().descriptionWithLocale(NSLocale.currentLocale())!)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!