按顺序对 NSDate 进行排序,同时忽略时间

发布于 2024-10-06 16:35:57 字数 87 浏览 0 评论 0原文

我想仅按日、月和年对 NSDate 数组进行排序,而不是按任何时间单位进行排序。我怎样才能做到这一点,因为我看不到一种方法来“取出” NsDate 的各个部分。

I want to sort an array of NSDates only on their day month and year so not on any of the units of time. How can I do this because I can't see a way of getting the individual parts of an NsDate "out".

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

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

发布评论

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

评论(1

半仙 2024-10-13 16:35:57

请参阅这篇文章,了解如何对包含 NSDate 对象的数组进行排序:

对 NSArray 进行排序日期字符串或对象

和我的用于删除时间:

截断 NSDate (零- out time)

ADDITION

1) 循环遍历 NSDate 对象数组,删除(清零)时间分量,并将它们添加到新数组中:

NSMutableArray *newDateArray = [NSMutableArray array];
for (NSDate *d in myDateArray)
{
    unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:flags fromDate:d];
    //Taking the time zone into account
    NSDate *dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
    [newDateArray addObject:dateOnly];
}

2) 现在您有了一个新数组由具有归零时间分量的 NSDate 对象组成,您可以对它们进行排序:

[newDateArray sortUsingSelector:@selector(compare:)];

此行使用 NSDate 对象自己的比较器方法对数组进行排序。

See this post for sorting an array containing NSDate objects:

Sort NSArray of date strings or objects

and mine for removing the time:

Truncate NSDate (Zero-out time)

ADDITION

1) Loop through your array of NSDate objects, removing (zeroing) the time components, and adding them to a new array:

NSMutableArray *newDateArray = [NSMutableArray array];
for (NSDate *d in myDateArray)
{
    unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:flags fromDate:d];
    //Taking the time zone into account
    NSDate *dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
    [newDateArray addObject:dateOnly];
}

2) Now that you have a new array consisting of NSDate objects with zeroed time components, you can sort them:

[newDateArray sortUsingSelector:@selector(compare:)];

This line sorts the array using the NSDate object's own comparator method.

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