gpt4 book ai didi

ios - NSDateComponentsFormatter 的方法 stringFromDate :ToDate: is returning a different value every second

转载 作者:行者123 更新时间:2023-12-01 18:11:45 25 4
gpt4 key购买 nike

我正在尝试获取今天日期和 future 日期之间的天数。
我每秒调用以下命令:

NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2025];
[components setMonth:1];
[components setDay:1];

NSDate *currentDate = [NSDate date];
NSDate *futureDate = [[NSCalendar currentCalendar] dateFromComponents:components];

NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorNone;
formatter.allowedUnits = NSCalendarUnitDay;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleAbbreviated;
NSString *remainingDaysAsString = [formatter stringFromDate:currentDate toDate:futureDate];

我每秒打印一次变量 leftDaysAsString 并且它总是每天不同。
3,551d
3,551d
3,550d
3,550d
3,551d
3,550d
3,551d

有没有人经历过类似的事情?这看起来像是类(class)的错误吗?

最佳答案

这很奇怪,看起来像一个错误。 NSDateComponentsFormatter的结果如果您指定,则正确(在我的测试中)
所有单位都小到秒:

formatter.allowedUnits = NSCalendarUnitDay + NSCalendarUnitHour + NSCalendarUnitMinute  + NSCalendarUnitSecond;

获取两个日期之间的天数的一种更简单可靠的方法是
NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSCalendarUnitDay
fromDate:currentDate
toDate:futureDate
options:0];
NSInteger days = comp.day;

关于ios - NSDateComponentsFormatter 的方法 stringFromDate :ToDate: is returning a different value every second,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29588607/

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