How to compare current system time with an array of times - ios

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;
}
}

Related

how to convert string date to nsdate using formatter?

i follow stackOverflow answer and Write a code but i Don't know What happen.it won't work. plz,any one can solve it for me. i use fooling code....
NSMutableArray *movieDate;
NSArray *temp1 = [_dicUpcomingMovie objectForKey:#"results"];
for (NSDictionary *temp2 in temp1)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *datestring = [temp2 valueForKey:#"release_date"];
//NSDate *myDate = [[NSDate alloc]init];
[formatter setDateFormat:#"dd MMM,YYYY"];
NSDate *date = [formatter dateFromString:datestring];
NSLog(#"%#",date);
[movieDate addObject:date];
NSLog(#"%#",movieDate);
}
so this is it. the above code was not work myDate object still nil
I believe that datestring doesn't match the format you specified. See NSDateFormatter for a complete example.
NSMutableArray *movieDate=[[NSMutableArray alloc]init];;
NSArray *temp1 = [_dicUpcomingMovie objectForKey:#"results"];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
for (int i=0 ;i<temp1.count;i++)
{
NSString *datestring = [[temp1 objectatindex:i]valueForKey:#"release_date"];
[serverFormatter setTimeZone:[NSTimeZone localTimeZone]];
[serverFormatter setDateFormat:#"dd,MMM,YYYY"];
NSDate *date = [serverFormatter dateFromString:dateString1];
[movieDate addObject:date];
}
NSLog(#"%#",movieDate);
Try this,
NSMutableArray *movieDate;
NSArray *temp1 = [_dicUpcomingMovie objectForKey:#"results"];
for (NSDictionary *temp2 in temp1)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *datestring = [temp2 valueForKey:#"release_date"];
//NSDate *myDate = [[NSDate alloc]init];
[formatter setDateFormat:#"dd MM,YYYY"];
NSDate *date = [formatter dateFromString:datestring];
NSLog(#"%#",date);
[movieDate addObject:date];
NSLog(#"%#",movieDate);
}

How to convert NSArray to NSDate

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;
}

separate future date in nsmutablearray

I am having a mutable array in that array i am having only past date, current date & future date. I have to separate the future date & store into another array. Can you help me.
This is my array:
uniqueItems(
"2015-03-01",
"2015-02-28",
"2015-02-22",
"2015-02-21",
"2015-02-20",
"2015-02-15",
"2015-02-14",
"2015-02-13",
"2015-02-08",
"2015-02-07",
"2015-02-01",
"2015-01-31",
"2015-01-30",
"2015-01-25",
"2015-01-24",
"2015-01-18",
"2015-01-17",
"2015-01-16",
"2015-01-11",
"2015-01-10",
"2014-12-07"
I have tried this coding, but is not working.
NSDate *currentDate = [NSDate date];
NSDate* dateAdded=(NSDate*)[uniqueItems objectAtIndex:0];
double min = [currentDate timeIntervalSinceDate:dateAdded];
int minIndex = 0;
for (int i = 1; i < [uniqueItems count]; ++i)
{
double currentmin = [currentDate timeIntervalSinceDate:[uniqueItems objectAtIndex:i]];
if (currentmin < min) {
min = currentmin;
minIndex = i;}}
you can use NSPredicate block for that. your array does not contain NSDate objects so we need to convert it into NSDate and then compare with [NSDate date]
NSPredicate *findFutureDates = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *dd = [df dateFromString:(NSString *)obj ];
return ([[NSDate date] compare:dd] == NSOrderedAscending);
}];
NSArray *arrFutureDates = [yourArray filteredArrayUsingPredicate: findFutureDates];
NSLog(#"%#",arrFutureDates);
if you pass NSOrderedAscending will give you future dates if you pass NSOrderedDescending will give you past dates.
NSDate *currentDate = [NSDate date];
NSDate *date;
int offset = 0;
NSMutableArray *futureArray = [[NSMutableArray alloc] init];
for (int i = 1; i < [uniqueItems count]; ++i)
{
date = [uniqueItems objectAtIndex:i];//TODO: Convert to NSDate
offset = [currentDate timeIntervalSinceDate:date];
if (offset < 0) {
[futureArray addObject:[uniqueItems objectAtIndex:i]];
}
}
This is a idea. Sorry, I'm coding in notepad without test.
Your array is of string format not an NSDate object. You can convert a string to nsdate
NSString *dateString = #"2010-02-13";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
and then you could do your check.

Issues with stringWithFormat

Please how do I make my stringWithFormat/initWithFormat to display am/pm instead of 24hrs, even though users selects am/pm from the pickerviewer? When a user select time; eg 4:15 pm, instead of it to display 4:15pm as confirmation, it displays 16:15 instead. I want it as 4:15pm. PLEASE HELP!!
-(IBAction)datePickerValueChanged:(id)sender
{ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setDateFormat:#"h:mm:ss a"];
NSString *strDate = [dateFormatter stringFromDate:self.pick.date];
dateArray = [strDate componentsSeparatedByString:#":"];
NSDate *current = [NSDate date];
NSString *currentTime = [dateFormatter stringFromDate:current];
NSArray *currArray = [currentTime componentsSeparatedByString:#":"];
curr = [currArray[0] intValue]*60 + [currArray[1] intValue];
min = [currArray[0] intValue]*60 + [currArray[1] intValue] + 30;
next = [[dateArray objectAtIndex:0] intValue]*60 +[[dateArray objectAtIndex:1] intValue];
....This is where values are displayed:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
time = [[NSString alloc]initWithFormat:#"%#T%#:%#:00",strDate, [dateArray objectAtIndex:0], [dateArray objectAtIndex:1]];
NSString *msg = [[NSString alloc] initWithFormat:#"%# %# %# %# ?", NSLocalizedString(#"do_ticket", nil), self.category.description,NSLocalizedString(#"at", nil),[[NSString alloc]initWithFormat:#"%#:%#", [dateArray objectAtIndex:0], [dateArray objectAtIndex:1]]];
alert_tick = [[UIAlertView alloc] initWithTitle:nil
message:msg
delegate:self
cancelButtonTitle:nil
otherButtonTitles:NSLocalizedString(#"Yes", nil), NSLocalizedString(#"No", nil), nil];
[alert_tick show];
}
Use NSDateFormatter. It doesn't matter that server values are given in 24h format, because your date formatting string can accommodate that (i.e. instead of using "h" for hours when calling setDateFormat:, which represents am/pm format, use "H" for 24h format).
Use the format #"hh:mm a" instead.
Example:
NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"];
NSDate *formattedDate = [formatter stringFromDate:today];
NSLog(#"date : %#", formattedDate);
Output:
date : 09:58 AM

NSDateFormatter not working in TextField

OK, I know I am missing something but I don't know what.
My NSDateFormmater comes up in the textField(personMonthdayTextField) with todays date but when I selected the datePicker and input it into the textField, it comes up with the standard format with the hours, minutes, seconds which I don't need.
Any help is appreciated.
Thanks
-(void)viewDidLoad {
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MMM/yyyy"];
NSString* str = [formatter stringFromDate:date];
NSLog(#"%#",str);
NSMutableArray *Arr=[str componentsSeparatedByString:#" "];
personMonthdayTextField.text=[Arr objectAtIndex:0];
}
- (IBAction)done:(id)sender {
NSDate *dateSelected = [datepick date];
NSString *dateStamp = [[NSString alloc]initWithFormat:#"%#", dateSelected];
personMonthdayTextField.text = dateStamp;
}
This will give you date only
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
datelabel.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:[NSDate date]]];
Adapt this for your code under your IBAction method
just use NSDateFormatter in your IBAction
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *dateSelected = [datepick date];
personMonthdayTextField.text = [dateFormatter stringFromDate:dateSelected];
you can also tweak with formats of date give in Apple ios sdk ,easily to get desired format.
If you only want the day why don't you set the dateFormat as "dd", it would save the need to separate the components of dateString.
-(void)viewDidLoad {
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd"];
personMonthdayTextField.text = [formatter stringFromDate:date];
}
- (IBAction)done:(id)sender {
NSDate *dateSelected = [datepick date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd"];
personMonthdayTextField.text = [formatter stringFromDate:date];
}

Resources