gpt4 book ai didi

ios - 两个日期之间经过的天数总是相差一天

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

我正在尝试计算两个日期之间的天数。这是我的做法:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

unsigned int calendarFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDate *dateToCheck = (self.subscriptionEnd ?: self.trialEnd);
NSLog(@"dateToCheck: %@", dateToCheck);
NSLog(@"current date: %@", [self systemTimeZoneDate]);
NSDateComponents *components = [gregorian components:calendarFlags
fromDate:[self systemTimeZoneDate]
toDate:dateToCheck
options:0];
return [components day] >= 0 ?: 0;

在撰写本文时,NSLog 输出以下内容:

2014-09-05 22:56:20.054 tweepy[9635:60b] dateToCheck: 2014-10-05 08:02:51 PM +0000
2014-09-05 22:56:20.057 tweepy[9635:60b] current date: 2014-09-05 10:56:20 PM +0000

它返回一天的差异,因为 iOS 认为该天采用 YDM 格式。

我应该在某处指示日期格式吗?

以下是如何设置 self.subscriptionEnd 的代码:

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 30;
self.subscriptionEnd = [gregorianCalendar dateByAddingComponents:dateComponents toDate:[self systemTimeZoneDate] options:0];

以下是如何设置 self.TrialEnd 的代码:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 2;
self.trialEnd = [gregorian dateByAddingComponents:dateComponents toDate:[self systemTimeZoneDate] options:0];

最佳答案

日期格式与它没有任何关系。正在发生的事情是 NSDateComponents 为您提供了您所要求的,即年、月和日的总差异。如果您只需要天数,则只需提供 NSDayCalendarUnitdocs说清楚:

Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days.

关于ios - 两个日期之间经过的天数总是相差一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694676/

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