0

私は次のObjective-Cコードを持っています。dateServer、dateClientは同じ値を示していますが、実際には異なるはずです。そのため、timeDiffはnullになります。

NSDate *dateClient  = [NSDate date];

[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"PDT"]];
NSDate *dateServer = [NSDate date];

NSLog(@"dateServer=%@",[dateServer description]);
NSLog(@"dateClient=%@",[dateClient description]);

NSTimeInterval timeDiff = [dateClient timeIntervalSinceDate:dateServer];

NSString *dateStr = @"2012-09-21 05:34:24";

// Convert string to date object
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *dateNew = [formatter2 dateFromString:dateStr];  
NSLog(@"date new %@" , [dateNew description]);

最後に、date newは、指定された文字列以外のものになります。なぜこれが起こっているのですか、私は文字列を日付に変換したいだけです。誰かが両方の場所で何が間違っている可能性があるかを提案できますか?前もって感謝します。

4

2 に答える 2

1

以下のコードを使用してください

NSDate* dateClient = [NSDate date];

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"PDT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:dateClient];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:dateClient];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSTimeInterval

于 2012-09-21T12:14:40.347 に答える
0

[NSDate日付]; あなたに現在の時間を与えています。したがって、dateClientとdateServerの間のtimeIntervalを比較します。どちらも、現在の時刻を保持します。そのため、timeDiffの結果はゼロになります。

于 2012-09-21T12:13:37.193 に答える