如何在 NSDate 中跳过时间?

发布于 2024-12-26 10:32:45 字数 286 浏览 1 评论 0原文

我想获得跳过时间的日期之间的差异,这意味着如果一个日期是 2012 年 1 月 13 日 - 晚上 11 点,另一个日期是 2012 年 1 月 14 日 - 上午 12 点,那么差异应该是 1 天而不是 0 天。我的意思是我只想要日期之间的差异, 2012年1月14日至2012年1月13日,跳过时间。我知道我可以使用 NSDate api 来计算差异,但问题是它也考虑时间。所以我想在计算差异时我会跳过时间,但我不知道如何跳过时间,因为如果我使用 NSDateFormatter 它将返回字符串而不是日期。请帮助我我能做什么?

提前致谢!

I want to get difference between dates skipping time means if one date is 13 Jan 2012 - 11 pm and other date is 14 Jan 2012 - 12 am,then difference should be 1 day not 0 day.I mean I want difference between date only, 14 Jan 2012 - 13 Jan 2012, skipping time. I know I can use NSDate api to calculate difference but the problem is it consider time also.So I thought while calculating difference I will skip time but I do not know how to skip time because if I use NSDateFormatter it will return string not date.Please help me what I can do?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吾性傲以野 2025-01-02 10:32:45

您需要做的是首先获取每个日期的NSDateComponents。一旦你这样做了,你就可以比较“日”部分来获得差异。

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 = ....;
NSDate *date2 = ....;
NSDateComponents *comps1 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date1];
NSDateComponents *comps2 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date2];

date1 = [cal dateFromComponents:comps1];
date2 = [cal dateFromComponents:comps2];

NSDateComponents *diffComps = [cal components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0];

NSLog(@"Days diff = %d", diffComps.day);

日期 API 可能会让您觉得有点奇怪,但一旦您使用它,它就会非常强大。

What you need to do is get the NSDateComponents of each date first. Once you do that you can compare the 'day' component to get you difference.

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 = ....;
NSDate *date2 = ....;
NSDateComponents *comps1 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date1];
NSDateComponents *comps2 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date2];

date1 = [cal dateFromComponents:comps1];
date2 = [cal dateFromComponents:comps2];

NSDateComponents *diffComps = [cal components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0];

NSLog(@"Days diff = %d", diffComps.day);

The date API can be kind of weird to wrap your head around, but once you do it is quite powerful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文