I am having an array which having a date. I want to convert the array into NSDate. Then converted NSDate are stored in an another array.This is my array.
uniqueItems (
"2015-02-17",
"2015-02-09",
"2015-02-02",
"2015-01-27",
"2015-01-19",
"2015-01-12"
)
How to convert this array to NSDate, And store in to another array. Help me in coding.
Suppose you have an array as below:
NSArray *ary = [NSArray arrayWithObjects:#"2015-02-17",#"2015-02-09",#"2015-02-02", nil];
To convert each string into date:-
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
for(int i =0;i<ary.count;i++){
NSDate *d = [[NSDate alloc]init];
d = [dateFormatter dateFromString:ary[i]];
}
If you want to use NSDateFormate, you can also use in loop also.
First convert your NSString to NSDate
NSArray *arrr = #[ #"2015-02-17",
#"2015-02-09",
#"2015-02-02",
#"2015-01-27",
#"2015-01-19",
#"2015-01-12"];
NSMutableArray *arrDates = [[NSMutableArray alloc]init];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
for (int i = 0; i<arrr.count; i++) {
[arrDates addObject:[df dateFromString:arrr[i]];;
}
NSLog(#"%#",arrDates);
now sort array for dates because your array contains NSDate Objects. you don't have key so do not pass any key
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
sortDescriptorWithKey:#""
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedDateArray = [arrDates sortedArrayUsingDescriptors:sortDescriptors];
NSLog(#"%#",sortedDateArray);
I can understand as you are a newbie,Follow these steps but remember to get the understanding first:-
1.Enumerate your array to get all the strings(dates for your understanding),and add those to another array you want, like this:-
for (NSString *dateString in yourArrayofDates) {
NSDate *date=[self getDateFromDateString:dateString];
[yourAnotherDateArray addObject:date];
}
2.Add a method to get the NSDate from your string,like this:-
-(NSDate *)getDateFromDateString :(NSString *)dateString {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:dateString];
return date;
}
Related
I have a NSMutableArray that contains dates in string format. Here I need to sort that array in order of ascending order of dates. I used strong text
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:#"self" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];
But it only sort the dates in terms of ascending order of day and month. Year is not considered. Please help me.
For example, Array contains
03/09/2017, 03/06/2016, 01/06/2016,01/04/2016 and 03/01/2017.
After using the above lines of code, Array contains like,
01/04/2018, 01/06/2016, 03/01/2017, 03/06/2016, 03/09/2016
You need to use sortedArrayUsingComparator like this way to sort date with String array.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
NSDate *d1 = [df dateFromString: obj1];
NSDate *d2 = [df dateFromString: obj2];
return [d1 compare: d2];
}];
Note : Set formate of date According to your date, it is hard to predicate date formate from your example thats why I have used MM/dd/yyyy, if your date contain formate dd/MM/yyyy then use that.
your code is correct but date format wrong.
try this code:
NSMutableArray *dateArray = [[NSMutableArray alloc] initWithArray: #[#"03/09/2017", #"03/06/2016", #"01/06/2016",#"01/04/2016", #"03/01/2017"]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date;
for (int i = 0; i < dateArray.count; i++) {
[formatter setDateFormat:#"MM/dd/yyyy"]; // Please your date format set.
date = [formatter dateFromString:[dateArray objectAtIndex:i]];
[formatter setDateFormat:#"yyyy/MM/dd"];
[dateArray replaceObjectAtIndex:i withObject:[formatter stringFromDate:date]];
}
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:#"self" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Array: %#",reverseOrder);
Please try below code:
NSArray *strDateArray = [[NSArray alloc] initWithObjects:#"03/09/2017",#"03/06/2016", #"01/06/2016",#"01/04/2016",#"03/01/2017", nil];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSMutableArray *dateArray = [[NSMutableArray alloc] init];
for (NSString *dateString in strDateArray) {
NSDate *date = [formatter dateFromString:dateString];
[dateArray addObject:date];
}
// sort array of dates
[dateArray sortUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2) {
// return date1 compare date2 for ascending. And reverse the call for ascending.
return [date1 compare:date2];
}];
NSLog(#"dateArray %#", dateArray);
NSMutableArray *sortedDateArray = [[NSMutableArray alloc] init];
for (NSDate *date in dateArray) {
NSString *dateString = [formatter stringFromDate:date];
[sortedDateArray addObject:dateString];
}
NSLog(#"sortedDateArray %#", sortedDateArray);
For Swift 4.0
let formater = DateFormatter()
formater.dateFormat = "MM/dd/yyyy" //date formate should be according to your date formate
let sortedArray=arrayToSort.sorted(){
(obj1, obj2) in
let date1=formater.date(from: obj1)
let date2=formater.date(from: obj2)
return date1!<date2!
}
//You can change the date format according to your code
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSArray *sortedArray = [YourArraysortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2)
{
NSString *strDateObj1 = [NSString stringWithFormat:#"%#",[obj1 valueForKey:#"BirthDate"]];
NSString *strDateObj2 = [NSString stringWithFormat:#"%#",[obj2 valueForKey:#"BirthDate"]];
NSDate *d1 = [df dateFromString: strDateObj1];
NSDate *d2 = [df dateFromString: strDateObj2];
return [d1 compare: d2];
}];
NSLog(#"%#", sortedArray)
I have the following NSArray which contains a dictionary at each index , here is the content, just providing first 3 records-
[
{
"postDate": "4/11/2011 2:03:33 PM",
"imageLink": "",
"eventLink": "www.google.com"
},
{
"postDate": "6/16/2011 1:42:45 PM",
"imageLink": "",
"eventLink": "www.google.com"
},
{
"postDate": "9/21/2011 10:22:34 AM",
"imageLink": "",
"eventLink": "www.google.com"
}
]
NOTE:- postDate is just a NSString it is not coming in NSDate type, but I have to perform sort on basis of this key.
My task is to sort the array as per the "postDate" key , means the whole array will be sorted in order by date (ascending/descending).
I have used the following code, but didn't help as arr is storing the all the data from arrEventsData but sorting is not happening:-
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"postDate" ascending:YES];
NSMutableArray *arr = [[arrEventsData sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]mutableCopy];
Any idea or solution will help.
Thanks
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"M/dd/yyyy H:mm:ss a"];
NSArray *sortedByDates = [arr sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2)
{
NSDate *date1 = [dateFormatter dateFromString:obj1[#"postDate"]];
NSDate *date2 = [dateFormatter dateFromString:obj2[#"postDate"]];
return [date1 compare:date2];
}];
NSLog(#"Sorted Array : %#",sortedByDates);
Like this:
NSMutableArray *sortedArray = [arr sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSDate *d1 = [self stringToDate:obj1[#"postDate"]];
NSDate *d2 = [self stringToDate:obj2[#"postDate"]];
return [d1 compare:d2];
}];
For the "stringToDate" method, however you want to implement that, see another SO answer here: Convert NSString of a date to an NSDate
Edit: As #Droppy has pointed out, it would really be best to parse the string into a NSDate as soon as the data arrives from the server. That prevents expensive repeated conversion in sorting, and is probably all around more useful anyway.
You will have to create NSDate objects from those NSString's to make the compare work
Create a static NSDateFormatter as they are expensive to create:
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
static NSDateFormatter *dateFormatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; //Set correct format here
});
NSDate *first = [dateFormatter dateFromString:[a objectForKey:#"postDate"]];
NSDate *second = [dateFormatter dateFromString:[b objectForKey:#"postDate"]];
return [first compare:second];
}];
I want to sort array according to Dates and Months value.I am using this code
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc]initWithKey:#"self" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject:descriptor];
revereseorder=[dateAarray sortedArrayUsingDescriptors:descriptors];
NSLog(#"date order %#",revereseorder);
I have got the response like below:
date order (
"01-11-2014",
"01-12-2014",
"02-11-2014",
"02-12-2014",
"03-11-2014",
"03-12-2014",
"04-11-2014",
"04-12-2014",
"05-11-2014",
"05-12-2014",
"06-11-2014",
"06-12-2014",
"07-11-2014",
"07-12-2014",
"08-11-2014",
"08-12-2014",
"09-11-2014",
"09-12-2014",
"10-11-2014",
"10-12-2014",
"11-11-2014",
"11-12-2014",
"12-11-2014",
"12-12-2014",
"13-11-2014",
"13-12-2014",
"14-11-2014",
"15-11-2014",
"16-11-2014",
"17-11-2014",
"18-11-2014",
"19-11-2014",
"20-11-2014"
)
but i need to display the response current date to descending order based on the current month.Can you please suggest me how can its solve? thank you#
You'll need to convert the strings into actual NSDate objects if you want to sort them properly.
You can use the comparator function to sort them like this...
NSArray *dateStringArray = //your array...
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"dd-MM-yyyy";
NSArray *sortedArray = [dateStringArray sortedArrayUsingComparator:^(NSString *string1, NSString *string2) {
NSDate *date1 = [dateFormatter dateFromString:string1];
NSDate *date2 = [dateFormatter dateFromString:string2];
return [date1 compare:date2];
}];
If you want descending order then just change the last line of the comparator to...
return [date2 compare:date1];
Try this:
NSDateFormatter *fmtdt = [[NSDateFormatter alloc] init];
[fmtdt setDateFormat:#"dd-MM-yyyy"];
NSComparator compareTimes = ^(id string1, id string2)
{
NSDate *time1 = [fmtdt dateFromString:string1];
NSDate *time2 = [fmtdt dateFromString:string2];
return [time1 compare:time2];
};
NSSortDescriptor * sortDesc = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:compareTimes];
[yourArray sortUsingDescriptors:#[sortDesc]];
NSDateFormatter is the easy way, but if you do not want to use NSDateFormatter, then you have to tokenize each date by '-' and sort, this requires more processing though.
NSArray *token = [string componentsSeparatedByString: #"-"];
within my application I am parsing in dates as strings from an RSS feed and attempting to sort them by the date. When I do a standard sortDescriptor on the strings, it sorts fine, but because the format is "DD/MM/YYYY HH:MM:SS" it is being sorted by the day rather than the whole date, so my list is not in chronological order.
I am therefore attempting to convert the date string parsed from the RSS into an NSDate and then sort by the date. However, when I'm doing this it returns null. Can anyone specify where I'm going wrong?
// Loop through XML data
[rxml iterate:#"channel" usingBlock:^(RXMLElement *supportElement) {
[supportElement iterate:#"item" usingBlock:^(RXMLElement *repElement) {
// Assign element to string
NSString *title = [repElement child:#"title"].text;
NSString *description = [repElement child:#"description"].text;
NSString *imageurl = [repElement child:#"image"].text;
NSString *mystartDate = [repElement child:#"start_date"].text;
NSString *myendDate = [repElement child:#"end_date"].text;
// DESCRIPTION FORMATTING
description = [customStringParser parseHTML:description];
description = [customStringParser parseLinesMultiple:description];
description = [customStringParser removeSocialSignifiers:description];
currentFeed.description = description;
// DATE FORMATTING
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"DD/MM/YYYY HH:MM:SS"];
[dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
NSDate *startDate = [dateFormatter dateFromString:mystartDate];
NSDate *endDate = [dateFormatter dateFromString:myendDate];
currentFeed.startDate = startDate;
currentFeed.endDate = endDate;
NSLog(#"%#", startDate);
NSLog(#"%#", endDate);
// Add a new object to the feeds array
[eventsFeeds addObject:currentFeed];
}];
[loadingView removeFromSuperview];
[self.loadingIndicator stopAnimating];
//sort array
NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:#"startDate" ascending:NO];
[eventsFeeds sortUsingDescriptors:[NSArray arrayWithObject:sortByDate]];
I also then believe I may have to convert the NSDate back to a string so that it can be printed within my detailTextLabel on the view controller, is this correct? Thanks.
You should change:
[dateFormatter setDateFormat:#"DD/MM/YYYY HH:MM:SS"];
to
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSArray *arr = [folderContent sortedArrayUsingFunction:dateSort context:nil];
//The date sort function
NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *d1 = [formatter dateFromString:[s1 substringFromIndex:[s1 length]-19]];
NSDate *d2 = [formatter dateFromString:[s2 substringFromIndex:[s2 length]-19]];
// return [d1 compare:d2]; // ascending order
return [d2 compare:d1]; // descending order
}
I am using the below code to try and use current system time to tell me the next time in the array. All it logs out is the last number in the array. I have searched, and this is how I ended up where I am, but could never get it to work just right. Thanks
self.array = #[#"00:15", #"01:35, "#"05:30", #"06:10", #"07:05", #"07:55", #"08:45", #"09:35", #"10:40", #"11:25", #"12:20", #"13:10", #"14:05", #"15:00", #"15:45", #"16:40", #"17:30", #"18:20", #"19:20", #"20:10", #"21:00", #"22:05", #"22:55"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm"];
NSDate *formattedCurrentDate = [dateFormat dateFromString:[dateFormat stringFromDate:[NSDate date]]];
for(NSString *stringTime in self.array) {
NSDate *dateFromString = [dateFormat dateFromString:stringTime];
if([formattedCurrentDate earlierDate:dateFromString]) {
self.nextTime.text = stringTime;
}
}
Your code is behaving exactly as it should, you are having it return an earlier time than the current time, which means every single time is assigned to self.nextTime.text, but you only see the very last assignment, which is the last item in the array.
Further more your if statement always returns true if executed correctly, so you will always get true unless you provide an object that is not an NSDate.
Here is the correct way of getting what you would like without having to worry about ordering your array.
NSArray *array = #[#"16:40", #"05:30", #"06:10", #"07:05", #"07:55", #"08:45", #"09:35", #"10:40", #"11:25", #"12:20", #"13:10", #"14:05", #"15:00", #"15:45", #"16:40", #"17:30", #"18:20", #"19:20", #"20:10", #"21:00", #"22:05", #"22:55", #"23:55", #"01:35"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm"];
NSDate *formattedCurrentDate = [dateFormat dateFromString:[dateFormat stringFromDate:[NSDate date]]];
NSDate *laterDate;
NSDate *closestDate;
for(NSString *stringTime in array) {
NSDate *dateFromString = [dateFormat dateFromString:stringTime];
laterDate = [formattedCurrentDate laterDate:dateFromString];
if(![laterDate isEqualToDate:formattedCurrentDate]){
closestDate = [laterDate earlierDate:closestDate];
}
}
NSLog(#"Closest Date: %#", [dateFormat stringFromDate:closestDate] );
NSArray *array = #[#"23:15", #"01:35", #"05:30", #"06:10", #"07:05", #"07:55", #"08:45", #"09:35", #"10:40", #"11:25", #"12:20", #"13:10", #"14:05", #"15:00", #"15:45", #"16:40", #"17:30", #"18:20", #"19:20", #"20:10", #"21:00", #"22:05", #"22:55", #"23:55"];
NSMutableArray *datesArray = [[NSMutableArray alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm"];
//Convert all strings to dates
for (NSString *str in array)
{
NSDate *formattedCurrentDate = [dateFormat dateFromString: str];
[datesArray addObject:formattedCurrentDate];
}
//Sort dates.
NSArray *sortedArray = [datesArray sortedArrayUsingSelector:#selector(compare:)];
NSString *date = [dateFormat stringFromDate:[NSDate date]];
NSDate *formattedTodatDate = [dateFormat dateFromString:date];
//Print the desired date
for(NSDate *stringTime in sortedArray)
{
if([formattedTodatDate compare:stringTime] == NSOrderedAscending)
{
NSLog(#"Result is %#", [dateFormat stringFromDate:stringTime]);
break;
}
}
Try the above code. I just followed what others have mentioned with sorting dates.
If you want a more generic solution, that doesn't depend on the order of the array, you could use the code below:
NSArray *array = #[#"02:25", #"01:35", #"05:30", #"06:10", #"07:05", #"07:55", #"08:45", #"09:35", #"10:40", #"11:25", #"12:20", #"13:10", #"14:05", #"15:00", #"15:45", #"16:40", #"17:30", #"18:20", #"19:20", #"20:10", #"21:00", #"22:05", #"22:55", #"23:55"];
NSDateFormatter *dateFormat = [NSDateFormatter new];
[dateFormat setDateFormat:#"HH:mm"];
NSDate *formattedCurrentDate = [dateFormat dateFromString:[dateFormat stringFromDate:[NSDate date]]];
NSTimeInterval currentInterval = [formattedCurrentDate timeIntervalSince1970];
NSTimeInterval smallerInterval = CGFLOAT_MAX;
for(NSString *stringTime in array) {
NSDate *dateFromString = [dateFormat dateFromString:stringTime];
NSTimeInterval dateFromStringInterval = [dateFromString timeIntervalSince1970];
NSTimeInterval actualInterval = (dateFromStringInterval - currentInterval);
if(actualInterval > 0 && actualInterval < smallerInterval){
smallerInterval = actualInterval;
self.nextTime.text = stringTime;
}
}
This code is getting the closest next hour of the current hour, independent of it's index inside the array. And doesn't require more allocations or any sorting of arrays, like #Sandeep solutions (that do works).
Explaining:
The actualInterval is getting the difference in seconds between all dates and the current date. This variable (which is a double, actually) will only be positive to future hours (past hours will be negative).
So, all the code is doing is getting the smaller difference between future hours. This is, I think, the best solution to this case.
Hope this helped.
if your function works fine.
change:
for(NSString *stringTime in self.array) {
NSDate *dateFromString = [dateFormat dateFromString:stringTime];
if([formattedCurrentDate earlierDate:dateFromString]) {
self.nextTime.text = stringTime;
}
}
to:
for(NSString *stringTime in self.array) {
NSDate *dateFromString = [dateFormat dateFromString:stringTime];
if([formattedCurrentDate compare:dateFromString] == NSOrderedAscending) {
self.nextTime.text = stringTime;
break;
}
}