仅按年月日比较 NSDate 对象

发布于 2024-09-13 00:41:02 字数 117 浏览 1 评论 0原文

如果我想使用compare方法来比较两天:

[day1 compare:day2] == NSOrderedAscending

如何仅按年月日进行比较?

If I want to use the compare method to compare two days:

[day1 compare:day2] == NSOrderedAscending

How to compare only by year-month-day?

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

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

发布评论

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

评论(2

万人眼中万个我 2024-09-20 00:41:02

一天有 86400 秒,因此如果您获取两个日期自参考日期以来的秒数,则可以将它们除以 86400 并比较这两个数字。

这将为您提供(以 days1days2 为单位)自 1970 年 1 月 1 日起过去的日期的天数。您可以然后比较它们。

int days1 = [date1 timeIntervalSince1970] / 86400;
int days2 = [date2 timeIntervalSince1970] / 86400;

There are 86400 seconds in a day, so if you get the number of seconds since a reference date for both dates, you can divide them by 86400 and compare the two numbers.

This will give you (in days1 and days2) the number of days for the dates that have passed since January 1st, 1970. You can then compare them.

int days1 = [date1 timeIntervalSince1970] / 86400;
int days2 = [date2 timeIntervalSince1970] / 86400;
梦忆晨望 2024-09-20 00:41:02

理想情况下,您希望编写如下内容:

if ([date1 isSameDayAs:date2]) {...}

您可以通过 NSDate 上的简单类别来实现此目的,例如:

@implementation NSDate (Extensions)
- (BOOL) isSameDayAs:(NSDate *)date2
{
    int days1 = [self  timeIntervalSince1970] / 86400;
    int days2 = [date2 timeIntervalSince1970] / 86400;
    return (days1 == days2);
}
@end

Ideally, you would like to write something like:

if ([date1 isSameDayAs:date2]) {...}

You can achieve this with a simple category on NSDate, sonething like:

@implementation NSDate (Extensions)
- (BOOL) isSameDayAs:(NSDate *)date2
{
    int days1 = [self  timeIntervalSince1970] / 86400;
    int days2 = [date2 timeIntervalSince1970] / 86400;
    return (days1 == days2);
}
@end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文