2013-08-03 42 views
5

Tôi cố gắng để chuyển đổi múi giờ sau để thiết bị múi giờ địa phương:iOS: chuyển đổi múi giờ UTC vào điện thoại múi giờ địa phương

2013-08-03T05:38:39.590Z 

Xin vui lòng cho tôi biết làm thế nào để chuyển nó sang múi giờ địa phương.

Tôi làm cách nào?

+0

trùng lặp có thể xảy ra [Làm thế nào để chuyển đổi thời gian theo múi giờ của các thiết bị iPhone?] (Http://stackoverflow.com/questions/1081647/how-to-convert-time-to-the-timezone-of-the-iphone-device) –

Trả lời

11

Múi giờ có thể được áp dụng cho NSDateFormatter, từ đó bạn có thể tạo biến NSDate được phân biệt bằng chênh lệch thời gian.

NSString* input = @"2013-08-03T05:38:39.590Z"; 
NSString* format = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; 

// Set up an NSDateFormatter for UTC time zone 
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init]; 
[formatterUtc setDateFormat:format]; 
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

// Cast the input string to NSDate 
NSDate* utcDate = [formatterUtc dateFromString:input]; 

// Set up an NSDateFormatter for the device's local time zone 
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init]; 
[formatterLocal setDateFormat:format]; 
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]]; 

// Create local NSDate with time zone difference 
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]]; 

NSLog(@"utc: %@", utcDate); 
NSLog(@"local: %@", localDate); 

[formatterUtc release]; 
[formatterLocal release]; 
1

Hãy thử như thế này:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"]; 
    NSDate* utcTime = [dateFormatter dateFromString:@"2013-08-03T05:38:39.590Z"]; 
    NSLog(@"UTC time: %@", utcTime); 

    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 
    [dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"]; 
    NSString* localTime = [dateFormatter stringFromDate:utcTime]; 
    NSLog(@"localTime:%@", localTime); 

Hy vọng nó sẽ giúp bạn ....

+0

Yessss nó đã làm. Cảm ơn nhiều bạn –

Các vấn đề liên quan