need to get central time in objective-c

亡梦爱人 提交于 2019-12-14 00:00:21

问题


I have app where i need to get the current time (CST). I'm trying to use the following code but the NDate is the same as GMT:

NSDate* date = [NSDate date];
    NSLog(@"Time is %@", [date description]);

    [NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];
    NSDate* nDate = [NSDate date];
    NSLog(@"Central time is%@", [nDate description])

回答1:


Beside the fact that the time has not timezone itself, but you have to add a calendar to set it in relation to a time zone as I described here, you should not use a tz abbreviation as described here.




回答2:


but the NSDate is the same as GMT

That's right, and if you look at the printout, it says that it is showing you GMT. Therefore, it is giving you the right answer — the date-time, right now, in terms of GMT. The current time CST is the GMT date-time it is showing you.

That is what description does. If that isn't what you wanted, why did you use description?




回答3:


An NSDate doesn't have a time zone. It's a moment in time. A moment exists across all time zones. The string it gives from -description has to pick a time zone in order to represent the moment, because that's the way we write dates and times, but which it picks is arbitrary. The time zone used for the description in no way represents any fundamental fact about the nature of the NSDate object.

If you want to format a date into a string, don't use -description because it's not well-defined. (For example, which time zone it uses has changed before with the version of OS X and could change again.) Use an NSDateFormatter. You can configure an NSDateFormatter with a time zone by setting its timeZone property.

If you want to get information about the date, like month, day, hour, minute, etc., use NSCalendar and NSDateComponents.



来源:https://stackoverflow.com/questions/30419103/need-to-get-central-time-in-objective-c

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