简体   繁体   English

如何按日期格式@“2013年8月”按升序排序NSArray字符串..?

[英]How to sort an NSArray of strings in date format @“Aug 2013” in ascending order..?

I have an array of NSString objects in the format... @"Aug 2013" @"July 2013" and so on... 我有一个NSString对象的数组格式... @"Aug 2013" @"July 2013" and so on...

I want to sort this array in ascending order .. Is getting the date first for individual value a good idea..? 我想ascending order对这个数组进行ascending order 。首先获取个别值的日期是一个好主意..?

An other solution in one block 一个块中的另一个解决方案

NSArray* array = [NSArray arrayWithObjects:@"Janvier 2012",@"Mars 2013", @"Juin 2013", @"Octobre 2012", nil];

NSArray* result = [array sortedArrayUsingComparator:^(id a, id b) {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM YYYY"];

    NSDate* datea = [dateFormat dateFromString:a];
    NSDate* dateb = [dateFormat dateFromString:b];

    return [datea compare:dateb];
}];

I see you prefer "stringly" (not a typo) typed variables. 我看到你更喜欢“字符串”(不是拼写错误)类型的变量。 They often end up giving you error like this. 他们经常最终会给你这样的错误。 What you really should do is to store dates as dates. 你真正应该做的是将日期存储为日期。 They compare nicely agains each other and you can do fancy date calculations with them. 他们彼此很好地比较,你可以用它们进行奇特的日期计算。 The same is true for numbers. 数字也是如此。

Then if you want to present them like "Aug 2013" or "July 2013" in the user interface: use a date formatter to format the dates into appropriate strings for display only . 然后,如果要在用户界面中显示“8月2013”​​或“2013年7月”:使用日期格式化程序将日期格式化为适当的字符串以仅显示


For this case the two main classes that you should look into (read the documentation and such) are: NSDate and NSDateFormatter . 对于这种情况,您应该研究的两个主要类(阅读文档等)是: NSDateNSDateFormatter NSCalendar and NSDateComponents should also prove useful. NSCalendarNSDateComponents也应该证明是有用的。

I address this kind of problem by using a category to switch back and forth between NSDate and NSString. 我通过使用类别在NSDate和NSString之间来回切换来解决这类问题。 I would solve this problem by converting to dates using the category, sorting, and then converting back. 我会通过使用类别转换为日期,排序,然后转换回来解决此问题。

My category looks like the following (you'd need to add similar methods to manage the month/year format that your strings have) 我的类别如下所示(您需要添加类似的方法来管理字符串所具有的月/年格式)

    #import "NSDate+Utils.h"


    @implementation NSDate (NSDate_Utils)

    + (NSDate *)dateFromI18NString:(NSString *)dateString
    {
        if (dateString == nil)
            return nil;
        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";
        NSDate *d = [dateFormatter dateFromString:dateString];
        return d;
    }

    - (NSString *)dateToI18NString
    {
        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";

        return [dateFormatter stringFromDate:self];

    }

我会使用NSArrayNSDate对象,并在需要时格式化它的内容。

You can sort your array by implement below code. 您可以通过以下代码实现对数组进行排序。

-(void)somemethod{
   NSArray *sortedArray = [[NSArray alloc]initWithArray:YOURARRAY];
   sortedArray = [sortedArray sortedArrayUsingFunction:dateSort context:nil];
  }       

Call below function as above to sort your array.(Update formater as per your date format of array ) 如上所述调用以下函数对数组进行排序。(根据数组的日期格式更新格式化程序)

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM yyyy"];

NSDate *d1 = [formatter dateFromString:s1];
NSDate *d2 = [formatter dateFromString:s2];

return [d1 compare:d2]; // ascending order
return [d2 compare:d1]; // descending order
}

I hope, It may help you. 我希望,它可以帮到你。

Try this 尝试这个

- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *unsortedArray =[[NSArray alloc]initWithObjects:@"July 2013",@"Aug 2013",@"Jun 2012", nil];
NSMutableArray *arrSorted = [NSMutableArray arrayWithArray:unsortedArray];
for(int i=0;i<[arrSorted count];i++)
{

    for(int j=i+1;j<[arrSorted count];j++)
    {
        NSDateFormatter *df=[[NSDateFormatter alloc] init];
        df.dateFormat=@"MMM yyyy";
        NSDate *date1=[df dateFromString:[arrSorted objectAtIndex:i]];
        NSDate *date2=[df dateFromString:[arrSorted objectAtIndex:j]];
        if([date1 compare:date2]== NSOrderedAscending)
        {
            [arrSorted exchangeObjectAtIndex:i withObjectAtIndex:j];
        }
    }
}
// ORDER_DESCEND
NSLog(@"%@",arrSorted);

arrSorted = [NSMutableArray arrayWithArray:[[arrSorted reverseObjectEnumerator] allObjects]];
// ORDER_ASCEND
NSLog(@"%@",arrSorted);

}
- (NSArray *)sortedDateArrayWithExistedArray:(NSMutableArray *) setExistedArray acending:(BOOL)ascendingBoolvalue
{

    NSArray *sortedArray = [setExistedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"dd MMM, yyyy"];

            NSDate *d1 = [formatter dateFromString:obj1[@"displayDate"]];
            NSDate *d2 = [formatter dateFromString:obj2[@"displayDate"]];
       // id =  [d1 compare:d2];
        if (ascendingBoolvalue)
        {
            return [d1 compare:d2];
        }
        else
        {
            return [d2 compare:d1];
        }
    }];

     return sortedArray;
}

set setExistedArray == yourArray set ascending parameter as yes or no based upon your requirement yes for ascending order no for descending order. set setExistedArray == yourArray将升序参数设置为yes或no,具体取决于您对降序的升序no的要求。

how to access this function 如何访问此功能

self.sortedArray = [[self sortedDateArrayWithExistedArray:self.yourArray Acending:NO] mutableCopy]; self.sortedArray = [[self sortedDateArrayWithExistedArray:self.yourArray Acending:NO] mutableCopy];

if yourArray is mutable place call mutable copy method otherwise no need 如果yourArray是可变的,则调用可变复制方法,否则不需要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM