Calculate Nearest time from array with Current Time - ios

I have got 6 objects in array of Time
NSMutableArray *time=[[NSMutableArray alloc]initwithObjects:12:30, 14:40, 16:50, 20:30, 21:49, 23:12,nil];
Current time = 17:12;
How should I calculate the nearest time with 8:12 from time_array ?
conclusion must be 20:30
I implemented many formula's like picking up the least value available after substracting the times but there is bugs in it and its not a perfect solution.
Can any one share there idea's to calculate the perfect nearest time in Objective C?
I have tried this
//// Calculating to fetch nearest time
NSDateFormatter *current_time_format = [[NSDateFormatter alloc] init];
[current_time_format setTimeZone:zone];
[current_time_format setDateFormat:#"HHmm"];
NSString *current_date_string=[current_time_format stringFromDate:[NSDate date]];
int current_time_int=[current_date_string intValue];
int nearest_time=10000;
int time_calculation=0;
if ([calculated_time_array count]>=6) {
[calculated_time_array removeAllObjects];
}
for (int i=0; i<[current_timings_array count]; i++) {
NSString *prayer_timings=[current_timings_array objectAtIndex:i];
prayer_timings=[prayer_timings stringByReplacingOccurrencesOfString:#":" withString:#""];
time_calculation=[prayer_timings intValue]-current_time_int;
NSLog(#"%d-%d=%d",[prayer_timings intValue],current_time_int,time_calculation);
NSString *length_value=[NSString stringWithFormat:#"%d",current_time_int];
NSLog(#"lenght_value= %d",[length_value length]);
[calculated_time_array addObject:[NSString stringWithFormat:#"%d",time_calculation]];
if (time_calculation<nearest_time && time_calculation>0) {
nearest_time=time_calculation;
}
NSString *time_string=[NSString stringWithFormat:#"%d",nearest_time];
int index=[calculated_time_array indexOfObject:time_string];
header_bg_image.image=[UIImage imageNamed:[NSString stringWithFormat:#"top%d_bg.png",index+1]];
NSMutableString *mu = [NSMutableString stringWithString:[NSString stringWithFormat:#"%d",nearest_time]];
if ([time_string length]==3) {
[mu insertString:#"0" atIndex:0];
[mu insertString:#":" atIndex:2];
}
NSString *time=[NSString stringWithFormat:#"%#",mu];
time=[current_timings_array objectAtIndex:index];
time=[time stringByReplacingOccurrencesOfString:#":" withString:#"."];
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh.mm"];
date1 = [formatter dateFromString:time];
date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
}
// Here I'm calculating the time difference
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];//[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;
// NSLog(#"%# %dh %dm", interval<0?#"-":#"+", ABS(hour), ABS(minute));
label_time_left.text=[NSString stringWithFormat:#"Time left %dh %dm",ABS(hour), ABS(minute)];

I have solved it with my own method, here it is as it may help someone else
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:zone];
[formatter setDateFormat:#"HHmm"];
current_time=[formatter stringFromDate:date];
int current_time_int=[current_time intValue];
nearest_time=2400;
for (int i=0; i<[current_timings_array count]; i++) {
NSString *prayer_timings=[current_timings_array objectAtIndex:i];
prayer_timings=[prayer_timings stringByReplacingOccurrencesOfString:#":" withString:#""];
int calculated_time=[prayer_timings intValue]-current_time_int;
NSLog(#"Nearest Timings %d-%d=%d",[prayer_timings intValue],current_time_int ,calculated_time);
NSString *last_object_time=[current_timings_array.lastObject stringByReplacingOccurrencesOfString:#":" withString:#""];
if (current_time_int>[last_object_time intValue]) {
NSLog(#"It is greated value %d",[last_object_time intValue]);
if (calculated_time<nearest_time ) {
nearest_time=calculated_time;
header_bg_image.image=[UIImage imageNamed:[NSString stringWithFormat:#"top%d_bg.png", i+1]];
}
}
else{
if (calculated_time<nearest_time && calculated_time>0) {
nearest_time=calculated_time;
header_bg_image.image=[UIImage imageNamed:[NSString stringWithFormat:#"top%d_bg.png", i+1]];
}
}
}

I assume you have NSDate objects in your array.
You could make a for cycle:
NSDate *minDate = time.lastObject;
NSTimeInterval minTimeInterval = [minDate timeIntervalSince1970];
NSTimeInterval current = [[NSDate date] timeIntervalSince1970];
for (NSDate *date in time) {
NSTimeInterval interval = [date timeIntervalSince1970];
if (labs(minTimeInterval - current) > labs(interval - current)) {
minDate = date;
minTimeInterval = interval;
}
}
// The minDate is the object you are looking for

Related

Converting multiple minutes digits (more than 2) minutes to NSDate

I am trying to parse a clock string composed by a multiple number of minutes and convert it to a NSDate using a NSDateFormatter.
An example of the string I am trying to parse is #"1234:56", where 1234 are the minutes of the clock and 56 the seconds. I tried to use a format such as #"mmmm:ss" but it returned nil.
In case it is possible, can anyone help me with this?
Thanks
I'm not sure about the thing that you want to do, but I suggest do something like that:
NSArray *timeArray = [#"1234:56" componentsSeparatedByString:#":"];
NSUInteger minutes = [[timeArray firstObject] integerValue];
NSUInteger seconds = [[timeArray lastObject] integerValue];
NSTimeInterval totalSeconds = minutes*60+seconds;
And then you should create a new date object and work with this.
NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
NSDateFormatter only works with legal date format and there is no 'mmmm'.You should get date by yourself:
NSString *str = #"234:56";
NSArray<NSString *> *components = [str componentsSeparatedByString:#":"];
NSInteger minute = 0;
NSInteger second = 0;
switch (components.count) {
case 1:
second = components[0].integerValue;
break;
case 2:
second = components[0].integerValue;
minute = components[1].integerValue;
break;
default:
break;
}
// then convert to hours.
Try this.
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timerLabel.text = timeString;
If you want to convert that to HH:mm:ss then my approach will be something like:
// assuming you wouldn't have any hours in the string and format will always be minutes:seconds
NSArray *timeArray = [#"1234:56" componentsSeparatedByString:#":"];
//array's firstObject will be the "minutes/Hours"
NSString *minutesAndHours = [timeArray firstObject];
int hours = [minutesAndHours intValue]/60;
int minutes = [minutesAndHours intValue]%60;
int seconds = [timeArray lastObject];
//create the format
NSString *time = [NSString stringWithFormat:#"%d:%d:%d",hours,minutes,seconds];
//then use the time format
NSString *time = [NSString stringWithFormat:#"%d:%d:%d",hours,minutes,seconds];
NSDateFormatter *format = [NSDateFormatter new];
[format setDateFormat:#"HH:mm:ss"];
NSDate *date = [format dateFromString:time];
something like this

Date and Time Format in iOS application

I am getting below date format from response
2015-12-23 05:17:04
But, I want to check date and time like,
date == today ?
date == yesterday ?
time == 1 hour
time == 2 hour till 9 hour
how to do it ?
To check whether date is today's, yesterday's, tomorrow's date etc... you can use NSDate-Extensions
ex:
NSDate *date = [self convertStringToDate:#"2015-12-24 12:40:04" formate:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"%d", [date isToday]);
NSLog(#"%d", [date isTomorrow]);
NSLog(#"%d", [date isYesterday]);
- (NSDate *)convertStringToDate: (NSString *)date formate:(NSString *)formate {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
[dateFormat setDateFormat:formate];
return [dateFormat dateFromString:date];
}
Use this method give you NSString back. you can compare string or time in method.
-(NSString* )AgoStringFromTime:(NSDate*)dateTime
{
NSDictionary *timeScale = #{#"sec" :#1,
#"min" :#60,
#"hr" :#3600,
#"day" :#86400,
#"week" :#605800,
#"month":#2629743,
#"year" :#31556926};
NSString *scale;
int timeAgo = 0-(int)[dateTime timeIntervalSinceNow];
if (timeAgo < 60) {
scale = #"sec";
} else if (timeAgo < 3600) {
scale = #"min";
} else if (timeAgo < 86400) {
scale = #"hr";
} else if (timeAgo < 605800) {
scale = #"day";
} else if (timeAgo < 2629743) {
scale = #"week";
} else if (timeAgo < 31556926) {
scale = #"month";
} else {
scale = #"year";
}
timeAgo = timeAgo/[[timeScale objectForKey:scale] integerValue];
NSString *s = #"";
if (timeAgo > 1) {
s = #"s";
}
return [NSString stringWithFormat:#"%d %#%#", timeAgo, scale, s];
}
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = [NSString stringWithFormat:#"yyyyMMddHHmmss"];
NSString *now = [dateFormatter stringFromDate:date];
You can try above code
Best wish
1.frist you can format your string to date,like this:
+ (NSDate *)dateFromString:(NSString *)dateString {
if (!dateString) {
return nil;
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
[formatter setLocale:[NSLocale currentLocale]];
NSDate *date= [formatter dateFromString:dateString];
return date;
}
2.then,you can use methods of NSDate,
+ (instancetype)date;//get current
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;//Returns the interval between the receiver and another given date.

Compare month and day of date in string to month and day of the current date

I have a JSON object that has several dates, for example: 15/12/2005 or 14/12/2012.
I need to do a comparison of the month and day with today's month and day; the year does not matter. I'm doing this:
-(void)setSingle:(NSDictionary*)object name:(NSString*)name {
NSMutableDictionary * content = [[NSMutableDictionary alloc] initWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:name]];
NSLog(#"%#", name);
if(name == #"teste") {
NSDate *dateReturn = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM"];
NSString * tempDate;
NSDictionary *dateObjectTemp = nil;
NSDictionary * dateObject = [object objectForKey:name];
for (NSDictionary*g in dateObject) {
tempDate = [g objectForKey:#"dia"];
dateObjectTemp = g;
NSLog(#"Data: %#", tempDate);
dateReturn = [dateFormatter dateFromString:tempDate];
NSLog(#"Data: %#", dateReturn);
[content setObject:dateObjectTemp forKey:tempDate];
}
} else {
NSDate *dateReturn = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString * tempDate;
NSDictionary *dateObjectTemp = nil;
NSDictionary * dateObject = [object objectForKey:name];
for (NSDictionary*g in dateObject) {
tempDate = [g objectForKey:#"dia"];
dateObjectTemp = g;
dateReturn = [dateFormatter dateFromString:tempDate];
[content setObject:dateObjectTemp forKey:tempDate];
}
}
NSDictionary* cont =content;
[[NSUserDefaults standardUserDefaults] removeObjectForKey:name];
[[NSUserDefaults standardUserDefaults] setObject:cont forKey:name];
}
This picks up the date, but dataReturn returns 2000-12-15. I want only the day and month.
and when will compare the next method
-(void)showContent{
if ( [self daysBetweenDate:currentDate andDate:self.dateLimit]>=0 ) {
NSDictionary *santododia = [super compareDate:currentDate name:#"santos"];
[self defineContent:[santododia objectForKey:#"texto"]];
self.urlShare = [santododia objectForKey:#"url"];
self.tituloShare = [santododia objectForKey:#"titulo"];
}else{
[self.webView loadHTMLString: #"<font color='black' style='font-family:sans-serif;'>Conteúdo indisponível, escolha a data de hoje ou anterior</font>" baseURL:nil];
}
}
Although the current date matches, the test is not passing.
-(void) defineContent:(NSString *)string{
string = [parentClass checkStringContent:string];
NSLog(#"Teste: %#", string);
if(string.length == 0){
string = #"<font color='black' style='font-family:sans-serif;'>nothing</font>";
} else {
string = [NSString stringWithFormat: #"%# %#", string , #"<style>body {color:#000 !important} .day{margin-top:5px} .month{margin-top:5px} </style>" ];
}
[self.webView loadHTMLString: string baseURL:nil];
}
To compare only parts of a date, you should use NSDateComponents. Parse your strings into NSDates using NSDateFormatter:
NSString * jsonDateString = #"15/12/2005";
NSDateFormatter * dF = [NSDateFormatter new];
// Format string must match date string!
dF.dateFormat = #"dd/MM/yyy";
NSDate * testDate = [dF dateFromString:jsonDateString];
NSDate * today = [NSDate date];
From there, you use NSCalendar to decompose that date and today's date into the pieces you're interested in:
NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents * todayComps = [cal components:NSCalendarUnitMonth|NSCalendarUnitDay
fromDate:today];
NSDateComponents * testComps = [cal components:NSCalendarUnitMonth|NSCalendarUnitDay
fromDate:testDate];
Then you can compare those date components objects:
[testComps isEqual:todayComps]
if the result is YES, then the two dates have the same day and month, ignoring the all other parts of the date, including the year.
try this to compare date -
NSDate *minDate ;
NSDate *maxDate ;
NSComparisonResult compareStart = [minDate compare: self.selectedDate]; // date1 is 6/6/2011 00:00
NSComparisonResult compareEnd = [maxDate compare: self.selectedDate]; // date2 is 9/6/2011 00:00
if ( ( (compareStart == NSOrderedAscending) || (compareStart == NSOrderedSame) ) && (compareEnd == NSOrderedDescending))
{
NSLog(#"date is in the right range");
}
else {
NSLog(#"Range is not valid .");
}

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.

NSString to NSDate return null value

Here i am getting current time and check whether its in am/pm format. If its not like that, i convert 24 hour time format into 12 hour time format and add AM/PM manually.
This is my code:
- (NSString *) getCurrentTime {
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"hh:mm:ss a"];
NSString *currentTime = [timeFormatter stringFromDate:today];
currentTime = [self checkTimeFormat:currentTime];
return currentTime;
}
And
- (NSString *) checkTimeFormat:(NSString *) currentTime
{
NSArray *timeArray = [currentTime componentsSeparatedByString:#":"];
int intHour = [[timeArray objectAtIndex:0] intValue];
NSString *lastVal = [timeArray objectAtIndex:2];
if ([lastVal rangeOfString:#"M"].location == NSNotFound) {
if (intHour < 12)
lastVal = [NSString stringWithFormat:#"%# AM", [timeArray objectAtIndex:2]];
else
lastVal = [NSString stringWithFormat:#"%# PM", [timeArray objectAtIndex:2]];
}
if (intHour > 12)
intHour = intHour - 12;
currentTime = [NSString stringWithFormat:#"%d:%#:%#", intHour, [timeArray objectAtIndex:1], lastVal];
NSLog(#"Current Time ==>> %#", currentTime);
return currentTime;
}
Conversion of NSString into NSDate code below:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate *testDate = [dateFormatter dateFromString:getCurrentTime];
NSLog(#"testDate => %#", testDate);
If the Time is in 12 hour format (am/pm), testDate value is getting correctly.
If the Time is in 24 hour format, testDate value is null
What is the issue?
Thanks in Advance.
You can try:
NSDate *today = [NSDate date];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
NSString *currentTime24 = [timeFormatter stringFromDate:today];
[timeFormatter setDateFormat:#"hh:mm:ss a];
NSDate *currentTime12 = [timeFormatter dateWithString:currentTime24];
NSString *currentTime = [timeFormatter stringWithDate:currentTime12];

Resources