0

I'm new to iOS and I'm trying to understand how to use dates and formatters to create a date object that represents the current time, but in the UTC time zone. That is, if my local time on my device is 3pm PST, I want to create a date object that represents the time 3pm UTC. I do NOT want to convert 3pm PST to the UTC equivalent, but instead create the 3pm UTC date using the 3pm PST local time date. My current code is...

NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
[dateFormatter setTimeZone:utcTimeZone];
NSString *nowInUTCString = [dateFormatter stringFromDate:[NSDate date]];

...but this essentially converts my local time to UTC time, which is what I do NOT want. I'm still reading up on the docs, but I thought I'd post this in the meantime. Any help?

Thanks so much in advance for your wisdom!

4

1 回答 1

4

You should let the system do all the date math for you. Doing date math yourself may lead to bugs.

We can use NSCalendar to convert dates to date components and back. NSDateComponents has a timezone property that we can set. We'll get back the date that represents it's timezone and components.

// grab the current calendar and date
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];

// create UTC date components
NSDateComponents *utcComponents = [cal components: NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit fromDate: now];
utcComponents.timeZone = [NSTimeZone timeZoneWithName: @"UTC"];

// get the UTC date
NSDate *utcDate = [cal dateFromComponents: utcComponents];

I'm in Pacific time and got the following printout.

NSLog(@"%@", utcDate); // 2013-08-29 12:09:52 +0000 (my time converted to UTC)
NSLog(@"%@", now);     // 2013-08-29 19:09:52 +0000 (right now in UTC)
于 2013-08-29T19:08:03.737 回答