我的应用程序从后端获取一些时隙并将其转换为当前时区 (PST) 并显示。在夏令时开始生效之前,一切都运行得很完美。
在 iOS 中有没有一种方法可以说给我这个 UTC 的 PST 日期和时间,它会自动处理夏令时。目前它转换得很好,但仍然给我一个小时的休息时间。
这是我正在做的:
-(NSDate *) toLocalTime:(NSDate*) currentDate
{
NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"US/Pacific"];
NSInteger seconds = [tz secondsFromGMTForDate: currentDate];
return [NSDate dateWithTimeInterval: seconds sinceDate: currentDate];
}
编辑
将我的代码更改为此但结果仍然相同:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.dateFormat = @"MM/dd/yyyy HH:mm:ss";
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *startDateString = [[self.slotsArray objectAtIndex:indexPath.row] objectForKey:@"StartDate"];
NSDate *startDate = [dateFormatter dateFromString:startDateString];
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.timeStyle = NSDateFormatterMediumStyle;
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/Los_Angeles"]];
NSString * dateString = [dateFormatter stringFromDate:startDate];
例如,当日光时间开始时,我正在显示 3 月 13 日的一些时间段。在 UTC 中,我得到的时间是 17:00,这相当于我们今天的 10 点。但在这种情况下,实际时间是那天的上午 9 点。我该如何解决?
最佳答案
我不知道该方法应该做什么,但是 NSDate
没有任何时区信息,所以如果您要将一个时区从一个时区“调整”到另一个时区,你这样做是错的。 NSDate
的文档甚至说
NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone.
如果你有一个 NSDate
并且你想在给定时区的本地时间将它呈现给用户,你可以这样做:
NSDate *date = // from somewhere
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterMediumStyle;
formatter.timeStyle = NSDateFormatterMediumStyle;
formatter.timeZone = [NSTimeZone timeZoneWithName:@"America/Los_Angeles"];
NSString *dateString = [formatter stringFromDate:date];
这将为您提供给定时区中正确日期的字符串,对于您输入的任何 NSDate
。不要尝试转换 NSDate
。
额外基于评论:
2016 年美国的夏令时从 3 月 13 日 02:00 开始。时间在那一刻向前移动了一个小时。如果您使用开始日期字符串 @"03/12/2016 17:00:00"
运行上述代码(在时间更改之前),最终结果为 Mar 12, 2016,上午 9:00:00
。如果您使用开始日期字符串 @"03/13/2016 17:00:00"
(时间更改后)运行它,则结果为 Mar 13, 2016, 10: 00:00 AM
。
因此,代码通过在夏令时开始前后返回不同的时间,以及在夏令时期间正确返回一天中较晚的时间,正确地调整了夏令时。你似乎得到了相同的结果,所以我不再确定你要解决什么问题。
关于ios - 将 UTC 时间转换为 PST 以获得夏令时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35730835/