gpt4 book ai didi

objective-c - 计算天数差异时结果不正确

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

我使用以下代码片段来查找两个日期之间的差异,结果相差一天:

NSString * dateString = @"2011-11-26" ;
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate * today = [[NSDate alloc] init];
NSDate * futureDate = [dateFormatter dateFromString:dateString];;
NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents * components = [gregorian components:unitFlags fromDate:today toDate:futureDate options:0];
NSLog(@"Number of days: %i",[components day]);
[today release];
[dateFormatter release];

天数:上面代码中的 6。实际上距离今天2011年11月19日已经7天了。

enter image description here

更新:以下工作正常。我重复代码了吗?

            NSString * dateString = @"2011-11-26" ;
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate * today = [NSDate date];

NSCalendar * greg = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSUInteger uf = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents * comp = [greg components:uf fromDate:today];
today = [greg dateFromComponents:comp];

NSDate * futureDate = [dateFormatter dateFromString:dateString];;
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents * components = [gregorian components:unitFlags fromDate:today toDate:futureDate options:0];

NSLog(@"Number of days: %ld",[components day]);

最佳答案

Apple 关于 components:fromDate:toDate: 的文档是这样说的:

The result is lossy if there is not a small enough unit requested to hold the full precision of the difference.

这意味着它想告诉您差异是“6 天 12 小时 31 分 2 秒...”,但您只要求天数,所以您返回 6。我的建议是首先将今天的日期四舍五入到午夜,以便距目标日期为整数天。

编辑:您可以通过要求 NSCalendar 为您提供 NSYearCalendarUnit | 来进行舍入。 NSMonthCalendarUnit | NSMonthCalendarUnit |今天的日期的 NSDayCalendarUnit ,然后从这些组件重新构造日期。 (分别使用 components:fromDate:dateFromComponents:。)

关于objective-c - 计算天数差异时结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8195441/

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