Iphone 如何从特定时区获取NSDate并基于该日期执行计算
我一直在努力思考Iphone 如何从特定时区获取NSDate并基于该日期执行计算,iphone,objective-c,ipad,Iphone,Objective C,Ipad,我一直在努力思考NSDate,NSCalendar,NSDateComponents,NSTimeZone和NSDateFormatter NSDate、NSTimeZone和NSDateFormatter非常简单。其他类则不是 我想得到当前的东部时间(代码运行时的实际日期/时间是EST) 然后我想把这个日期提前一个月,考虑到夏令时可能有效(也可能无效) 据我所知,增加84600是不恰当的做法,但我可能错了 有人能举个例子说明如何做到这一点吗?其实很简单: NSDate *now = [NSDa
NSDate
,NSCalendar
,NSDateComponents
,NSTimeZone
和NSDateFormatter
NSDate
、NSTimeZone
和NSDateFormatter
非常简单。其他类则不是
我想得到当前的东部时间(代码运行时的实际日期/时间是EST)
然后我想把这个日期提前一个月,考虑到夏令时可能有效(也可能无效)
据我所知,增加84600是不恰当的做法,但我可能错了
有人能举个例子说明如何做到这一点吗?其实很简单:
NSDate *now = [NSDate date];
NSDateComponents *oneMonth = [[[NSDateComponents alloc] init] autorelease];
[oneMonth setMonth:1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *oneMonthFromNow = [calendar dateByAddingComponents:oneMonth toDate:now options:0];
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
NSLog(@"Now in New York: %@", [df stringFromDate:now]);
NSLog(@"One month from now in New York: %@", [df stringFromDate:oneMonthFromNow]);
编辑:也就是说,你的问题措辞有点混乱。使用NSDate,您不需要在特定时区进行计算。您也不会得到“当前东部时间”。您只需获取当前时间点(不考虑时区)并对其进行计算。到特定时区的实际转换仅在输出时发生(当您向用户显示时间时,通常是在他们的时区)。让我来试一试,然后回到这里。