簡體   English   中英

iOS:將UTC時區轉換為設備本地時區

[英]iOS: convert UTC timezone to device local timezone

我想將以下時區轉換為設備本地時區:

2013-08-03T05:38:39.590Z

請讓我知道如何將其轉換為本地時區。

我該怎么做?

時區可以應用於NSDateFormatter ,您可以從中生成由時差區分的NSDate變量。

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

試試這樣:

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

希望它可以幫助你......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM