2013-08-20 56 views
0

請幫我解決問題。從dateFromString方法返回的日期

(我得到的firstDate,secondDate錯誤的日期。)(對於該值objValidation.aRange.MinimumValue,objValidation.aRange.MaximumValue來自Web服務)

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
       [df setDateFormat:@"MM/dd/yyyy"]; 
       [df setTimeZone:[NSTimeZone localTimeZone]]; 
       NSDate *myDate = [df dateFromString:inputString]; 
       [df setDateFormat:@"MM/dd/yyyy"]; 
       NSLog(@"objValidation.aRange.MinimumValue : %@,objValidation.aRange.MaximumValue :%@, inputString : %@",objValidation.aRange.MinimumValue,objValidation.aRange.MaximumValue,inputString); 
       NSDate *firstDate = [df dateFromString:objValidation.aRange.MinimumValue]; 
       NSDate *secondDate = [df dateFromString:objValidation.aRange.MaximumValue]; 
       NSLog(@"myDate : %@,firstDate :%@, secondDate : %@",myDate,firstDate,secondDate); 
       [df release]; 

輸出:

objValidation.aRange.MinimumValue : 8/20/2013 
objValidation.aRange.MaximumValue :12/31/9999 
inputString : 08/22/2013 
myDate : 2013-08-21 18:30:00 +0000 
firstDate :2013-08-19 18:30:00 +0000 
secondDate : 1999-12-30 18:30:00 +0000 
+0

請記住,NSLog會以UTC爲單位轉儲NSDate值,而不是印度時間。 –

+0

考慮到NSLog的時區偏移已經發布了大約100次,看起來沒問題。 –

+0

@MarcusAdams我嘗試刪除該行,但沒有幫助。它適用於iOS 5/5.1,但不適用於iOS 6/6.1 – Mahesh

回答

2

重新調整的日期是正確的,但您不考慮時區。

全部NSDate對象沒有時區。所以當你解析日期時系統時區將被使用。

+0

但在iOS 5/5.1模擬器中工作正常。它在iOS 6/6.1中失敗。 – Mahesh

+1

@Mahesh - 那麼真正的問題是,它爲什麼在5? –

+0

@HotLicks我不確定,爲什麼它在iOS 5中工作。他們是否有任何與dateFromString方法有關的問題?請告訴我。謝謝。 – Mahesh

-3

試試這個代碼:

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"MM/dd/yyyy"]; 
NSDate *date = [df dateFromString:@"8/20/2013"]; 
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; 
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date]; 
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date]; 
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset; 
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date]; 
NSLog(@"DateString : %@", destinationDate); 

你會得到你想要精確的輸出。

+0

這不適合我。 – Mahesh

+1

使用NSDateFormatter然後手動執行時區算術的簡單(而且容易出錯),比簡單地將格式化程序設置爲所需的時區。 –

相關問題