gpt4 book ai didi

objective-c - NSDateFormatter doesRelativeDateFormatting 返回意外的相对日期值

转载 作者:行者123 更新时间:2023-12-03 16:52:14 24 4
gpt4 key购买 nike

在 macOS 10.13.3 上使用 NSDateFormatter,当将 doesRelativeDateFormatting 设置为 YES 时,我得到的值不正确。我发现在格式化程序上使用自定义格式时可能存在相对日期问题,但我使用的是标准 dateStyletimeStyle 设置。

例如,使用适当配置的日期格式化程序而不使用 doesRelativeDateFormatting 将纽约市的当前日期与澳大利亚悉尼的日期进行比较,日期格式化程序输出的字符串正确显示了日期悉尼从纽约那天起+1。当我在相同的格式化程序上启用 doesRelativeDateFormatting 时,悉尼的相对日期错误地返回为同一天(“今天”)。演示这些结果的代码:

int main(int argc, char *argv[]) {
@autoreleasepool {
NSDate *now = [NSDate date];
NSDateFormatter *localDateFormatter = [NSDateFormatter new];
localDateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];
localDateFormatter.dateStyle = NSDateFormatterFullStyle;
localDateFormatter.timeStyle = NSDateFormatterFullStyle;

NSDateFormatter *remoteDateFormatter = [NSDateFormatter new];
remoteDateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Australia/Sydney"];
remoteDateFormatter.dateStyle = NSDateFormatterFullStyle;
remoteDateFormatter.timeStyle = NSDateFormatterFullStyle;

NSLog(@" Now in NYC: %@", [localDateFormatter stringFromDate:now]);
NSLog(@" Now in Sydney: %@", [remoteDateFormatter stringFromDate:now]);

localDateFormatter.doesRelativeDateFormatting = YES;
remoteDateFormatter.doesRelativeDateFormatting = YES;

NSLog(@" Relative now in NYC: %@", [localDateFormatter stringFromDate:now]);
NSLog(@"Relative now in Sydney: %@", [remoteDateFormatter stringFromDate:now]);
}
}

输出:

2018-01-26 14:42:28.478 Untitled[40694:1821879]             Now in NYC: Friday, January 26, 2018 at 2:42:28 PM Eastern Standard Time
2018-01-26 14:42:28.479 Untitled[40694:1821879] Now in Sydney: Saturday, January 27, 2018 at 6:42:28 AM Australian Eastern Daylight Time
2018-01-26 14:42:28.479 Untitled[40694:1821879] Relative now in NYC: Today at 2:42:28 PM Eastern Standard Time
2018-01-26 14:42:28.479 Untitled[40694:1821879] Relative now in Sydney: Today at 6:42:28 AM Australian Eastern Daylight Time

这是NSDateFormatter中的错误还是我在格式化程序的配置中做错了什么?谢谢。

最佳答案

你的输出是正确的。给世界上任何地方的任何人打电话并询问他们的日期是什么,他们都会说“今天”。仅仅因为世界上两个地方的这一天是一周中的不同一天,并不意味着所有地方都不是“今天”。

通过比较代码运行时两个不同日期的两个不同时区的输出,您会感到困惑。

“相对”日期格式的想法是输出是相对于给定时区中“现在”的字符串。它与任何其他时区无关。无论日期格式化程序中设置了哪一项。

关于objective-c - NSDateFormatter doesRelativeDateFormatting 返回意外的相对日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48468631/

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