NSDate change time zone

社会主义新天地 提交于 2019-12-04 03:58:36

问题


I am writing an app that involves time zone. I want to grab the user's device time, lets call that dateA, and I have a target date that will always be in EDT time zone (dateB).

I want to get the difference between the 2 dates and show the user, but in dateB's time zone.

eg:
user device time is 07:30AM PDT, and dateB is 11:00AM EDT.
So the time difference would be 30 minutes.

My algorithm is:
1) Get user device time
2) convert to EDT
3) grab the time difference between dateA and dateB

My issue is, after I get the user's device time [NSDate date], and go through DateFormatter with timezone EDT. The time does not change.

EDIT::

    NSDate *localDate = [NSDate date]; //this will have 7:30AM PDT
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"EDT"]];
    NSString *convertedTimeString = [dateFormatter stringFromDate:localDate];

How come the convertedTimeString does not contain 10:30AM in EDT? What am I doing wrong?


回答1:


A NSDate is stored in a timezone neutral way. It's up to the NSDateFormatter to actually format for a given timezone using -[NSDateFormatter setTimeZone:]. If you want a string from NSDate, there's also -[NSDate descriptionWithCalendarFormat:timeZone:locale:], but it's usually better to use a NSDateFormatter instead.



来源:https://stackoverflow.com/questions/18124684/nsdate-change-time-zone

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