簡體   English   中英

將日期轉換為設備時區

[英]Convert date to device timezone

我正在從服務器解析JSON,其中一個值是這樣的日期: 2013-01-21 18:22:35 +00000

我的問題是如何將此日期轉換為當地時間,例如2013-01-21 12:22:35 -0600

我需要將日期轉換為其他格式嗎?

謝謝!

編輯。

使用@Gabriele Petronella解決方案:

NSString * yourJSONString = @"2013-01-21 18:22:35 +0000";

NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
NSString* localAbbreviation = [localTimeZone abbreviation];

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"yyyy-MM-dd H:mm:ss Z"];
NSDate *aDate = [dateFormatter dateFromString:yourJSONString];

NSTimeZone *timezone = [NSTimeZone timeZoneWithName:localAbbreviation];
[dateFormatter setTimeZone:timezone];

NSLog(@"%@", [dateFormatter stringFromDate:aDate]);

一切正常!

您可以使用NSDateFormatterNSString讀取日期,然后可以使用另一個(可能是相同的) NSDateFormatter顯示更改時區的日期。

NSString * yourJSONString = @"2013-01-21 18:22:35 +0000";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle
 ];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];    
NSDate * aDate = [dateFormatter dateFromString:yourJSONString];

NSTimeZone * timezone = [NSTimeZone timeZoneWithName:@"America/Chicago"];
[dateFormatter setTimeZone:timezone];

NSLog(@"%@", [dateFormatter stringFromDate:aDate);

請注意,時區只是顯示的問題 ,而NSDate對象只是表示日期的抽象,它不受顯示的影響。

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
NSTimeZone *timeZone = [NSTimeZone localTimeZone]; [dateFormatter setTimeZone:timeZone];

NSString *myCurrentDeviceDate = [dateFormatter stringFromDate:[NSDate date]];

暫無
暫無

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

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