gpt4 book ai didi

iphone - 带有时区的日期时间对象在 Objective C 应用程序开发中不起作用

转载 作者:行者123 更新时间:2023-11-29 04:24:33 25 4
gpt4 key购买 nike

我有以下 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]);

最后,新日期将不同于指定的字符串。为什么会发生这种情况,我只想将字符串转换为日期。任何人都可以建议这两个地方可能出了什么问题吗?提前致谢。

最佳答案

使用下面的代码

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

关于iphone - 带有时区的日期时间对象在 Objective C 应用程序开发中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com