4

我正在编写一个涉及时区的应用程序。我想获取用户的设备时间,让我们调用它dateA,并且我有一个始终处于 EDT 时区 ( dateB) 的目标日期。

我想获得 2 个日期之间的差异并显示给用户,但在dateB's 时区。

例如:
用户设备时间是 07:30AM PDT,并且dateB是 11:00AM EDT。
所以时差是30分钟。

我的算法是:
1)获取用户设备时间
2)转换为 EDT
3)获取和之间的时间dateAdateB

我的问题是,在我获得用户的设备时间[NSDate date]后,DateFormatter使用时区 EDT。时间不变。

编辑::

    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];

为什么 convertTimeString 不包含 EDT 中的 10:30AM?我究竟做错了什么?

4

1 回答 1

2

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.

于 2013-08-08T11:25:07.900 回答