gpt4 book ai didi

ios - 奇怪的将输出从 NSString 转换为 NSDate

转载 作者:行者123 更新时间:2023-11-28 18:28:55 26 4
gpt4 key购买 nike

我在尝试从 NSString 输出 NSDate 对象时得到了奇怪的结果。我的 NSString 是:1976-06-11我的转换方法是:

-(NSDate*)dateFromString:(NSString *)dateString{

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateString];
return date;
}

但它输出 1976-06-10 21:00:00 +0000

怎么会这样? 1 天内的差异。

最佳答案

您有 UTC 格式的日期。使用此代码将您的日期转换为本地时间:

NSTimeInterval seconds; // assume this exists
NSDate *ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];

NSDateFormatter *utcFormatter = [[NSDateFormatter alloc] init];
utcFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
utcFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz";

NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init];
localFormatter.timeZone = [NSTimeZone timeZoneWithName:@"EST"];
localFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz";

NSString *utcDateString = [utcFormatter stringFromDate:ts_utc];
NSString *LocalDateString = [localFormatter stringFromDate:ts_utc];

或者您可以使用 [NSTimeZone defaultTimeZone] 来防止时区名称的硬编码字符串。如果没有设置默认时区,该方法返回系统时区。

关于ios - 奇怪的将输出从 NSString 转换为 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40716735/

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