开发者

How to get an NSDate from a specific time zone and perform calculations based on that date

I have been trying to wrap my head around NSDate, NSCalendar, NSDateComponents, NSTimeZone, and NSDateFormatter.

NSDate, NSTimeZone and NSDateFormatter are pretty straightforward. 开发者_StackOverflow社区 The other classes are not.

I want to get the current Eastern Time (the actual date/time is in EST at the moment the code is run).

Then I want to advance that date by exactly one month, taking into account daylight savings that may (or may not be) in effect.

From what I understand, adding 84600 is the improper way to do this, but I could be wrong.

Can someone please post an example of how to do this?


It's actually pretty easy:

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

Edit: That said, your question is phrased a little confusingly. With NSDate, you don't do calculations in a specific time zone. You also don't get the "current Eastern Time". You just get the current point in time (regardless of time zone) and do your calculations on it. The actual conversion to a specific time zone only happens at output (when you display the time to the user, usually in their time zone).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜