2013-03-06 19 views
-1

我有一個NSString這樣的:的NSDate調節到設備timzone

NSString *playTime = @"20:45";// GMT 

我需要將此字符串轉換爲NSDate(僅小時和秒),然後調節到設備時區。

實施例:

如果用戶設備時區設置爲GMT,我需要這樣的結果:@ 「20:45」;

如果用戶設備時區設置爲GMT + 2,我需要這樣的結果:@ 「22點45分」;

+0

你可以看看這裏的更多信息:http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class /Reference/Reference.html – MasterRazer 2013-03-06 13:37:43

+1

爲什麼你需要'NSDate'來做到這一點? – trojanfoe 2013-03-06 13:37:55

回答

1

試試這個

NSString *gmtDateString = @"20:45"; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
[dateFormatter setDateFormat:@"HH:mm"]; 

//Now you have date in GMT time zone by default dateFormatter timezone would be in local time zone 
NSDate *date = [dateFormatter dateFromString:dateString]; 

//set to local time zone 
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; 

//Now you have string in localDate format 
NSString *localDateString = [dateFormatter stringFromDate:date]; 
+0

謝謝@Anupdas它工作正常。 – user2139969 2013-03-06 13:53:22

+0

很高興幫助你:) – Anupdas 2013-03-06 13:59:29

0

按照您的要求使用此代碼進行日期轉換。

NSDateFormatter *dateFormat = [NSDateFormatter new]; 
    [dateFormat setDateFormat:@"HH:mm"]; 
    [dateFormat setTimeZone:[NSTimeZone localTimeZone]]; 
    logDate = [dateFormat dateFromString:@"20:45"]; 
    NSLog(@"Date %@",[dateFormat stringFromDate:logDate]); 
0

下面的代碼將計算時間w.r.t.當地時區。
假設我的時區是GMT+05:30所以時間05:30將成爲00:00

NSString *playTime = @"20:45"; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
formatter.dateFormat = @"HH:mm"; 
NSDate *date = [formatter dateFromString:playTime]; 
NSLog(@"%@",date); 

日誌是:2000-01-01 15:15:00 +0000