iphone - How to sort NSArray with date time values? -
i have nsarray
containing date/time nsstrings
in following format:
2/2/2011 2:46:39 pm 2/4/2011 11:59:47 …
where date represented month/day/year.
how sort nsarray making sure newest date/times @ top?
when you’re dealing dates, use nsdate
instead of nsstring
. also, it’s important consider time zone — web service provide dates in utc or other time zone?
you should first convert array of strings array of dates. otherwise, you’d converting string date whenever used comparison, , there more comparisons number of strings.
for example:
nsdateformatter *formatter = [[[nsdateformatter alloc] init] autorelease]; [formatter setdateformat:@"mm/dd/yyyy hh:mm:ss a"]; nsmutablearray *datearray = [nsmutablearray array]; (nsstring *datestring in array) { nsdate *date = [formatter datefromstring:datestring]; if (date) [datearray addobject:date]; // if date nil, string wasn't valid date. // add error reporting in case. }
this converts array
, array of nsstrings
, datearray
, mutable array of nsdates
. date formatter uses system time zone. if want use utc 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 array trivial:
[datearray sortusingselector:@selector(compare:)];
Comments
Post a Comment