如何使用日期时间值对NSArray进行排序

如何使用日期时间值对NSArray进行排序

本文介绍了如何使用日期时间值对NSArray进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSArray ,其中包含以下格式的日期/时间 NSStrings

I have an NSArray containing date/time NSStrings in the following format:

2/2/2011 2:46:39 PM
2/4/2011 11:59:47 AM
…

其中日期表示为月/日/年。

where the date is represented as month/day/year.

如何对NSArray进行排序以确保最新的日期/时间位于顶部?

How do I sort this NSArray making sure the newest date/times are at the top?

推荐答案

当你'处理日期,使用 NSDate 而不是 NSString 。此外,考虑时区很重要 - Web服务是否提供UTC或其他时区的日期?

When you’re dealing with dates, use NSDate instead of NSString. Also, it’s important to consider the time zone — does the Web service provide dates in UTC or some other time zone?

您应该首先将字符串数组转换为数组日期。否则,每当用于比较时,你都会将字符串转换为日期,并且会有比字符串数更多的比较。

You should first convert your array of strings into an array of dates. Otherwise, you’d be converting a string to a date whenever it is used for comparison, and there will be more comparisons than the number of strings.

例如:

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MM/DD/YYYY hh:mm:ss a"];

NSMutableArray *dateArray = [NSMutableArray array];
for (NSString *dateString in array) {
    NSDate *date = [formatter dateFromString:dateString];
    if (date) [dateArray addObject:date];
    // If the date is nil, the string wasn't a valid date.
    // You could add some error reporting in that case.
}

这会转换数组 ,一个 NSStrings 的数组,到 dateArray ,一个可变数组 NSDates 。日期格式化程序使用系统时区。如果您想使用UTC作为时区:

This converts array, an array of NSStrings, to dateArray, a mutable array of NSDates. The date formatter uses the system time zone. If you want to use UTC as the time zone:

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MM/DD/YYYY hh:mm:ss a"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

完成后,对数组进行排序非常简单:

Having done that, sorting the array is trivial:

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

这篇关于如何使用日期时间值对NSArray进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:30