get time between two times of the day - iphone

I've already tried with NSDate but with no luck.
I want the difference between for example 14:10 and 18:30.
Hours and minutes.
I Hope you can help me shouldn't be that complicated :)

There's no need to calculate this by hand, take a look at NSCalendar. If you want to get the hours and minutes between two dates, use something like this:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:firstDate
toDate:otherDate
options:0];
[gregorianCalendar release];
You now have the hours and minutes as NSDateComponents and can access them as NSIntegers like [components hour] and [components minute]. This will also work for hours between days, leap years and other fun stuff.

Here's my quick solution:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:#"HH:mm"];
NSDate *date1 = [df dateFromString:#"14:10"];
NSDate *date2 = [df dateFromString:#"18:09"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:#"%d:%02d", hours, minutes];

The NSDate class has a method timeIntervalSinceDate that does the trick.
NSTimeInterval secondsBetween = [firstDate timeIntervalSinceDate:secondDate];
NSTimeInterval is a double that represents the seconds between the two times.

NSString *duration = [self calculateDuration:oldTime secondDate:currentTime];
- (NSString *)calculateDuration:(NSDate *)oldTime secondDate:(NSDate *)currentTime
{
NSDate *date1 = oldTime;
NSDate *date2 = currentTime;
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int hh = secondsBetween / (60*60);
double rem = fmod(secondsBetween, (60*60));
int mm = rem / 60;
rem = fmod(rem, 60);
int ss = rem;
NSString *str = [NSString stringWithFormat:#"%02d:%02d:%02d",hh,mm,ss];
return str;
}

Related

How i can take the differece between two timings in iphone?

I have an application in which i need to show a label in the tableview as Xseconds ago and xminutes&yseconds ago,X hrs ago like that.i am doing like this `
NSString *todaysdateString=[dict objectForKey:#"sendingtime"];
NSString *time = todaysdateString;
NSString*todaysdateString1=[NSString stringWithString: #" "];
NSDate *date1;
NSDate *date2;
//{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
date1 = [formatter dateFromString:time];
date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
[formatter release];
//}
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];
float seconds = interval;
float hour = interval / 3600;
float minute =(interval - hour*3600) / 60;
NSLog(#"%02.0f,%02.0f,%02.0f",hour, minute, seconds);
`But this wont giving me the desired answers,I am getting like -0,00,-297 that is utterly wrong.Can anybody point me in where i am going wrong..
Use a NSCalendar to do this, maybe this code helps you
NSCalendar *c = [NSCalendar currentCalendar];
NSDateComponents *components = [c components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
fromDate:initialDate
toDate:endDate
options:0];
and in the components variables you will have the differences, get it back using: components.day, components.minute and components.second
As your seconds is in negative, you should swap your date here
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];
to :
NSTimeInterval interval = [date2 timeIntervalSinceDate: date1];
And can do as :
NSInteger intervalInt=interval;
NSInteger seconds = intervalInt % 60;
NSInteger minutes = (intervalInt / 60) % 60;
NSInteger hours = intervalInt / (60 * 60);
NSString *result = [NSString stringWithFormat:#"%02ld:%02ld:%02ld", hours, minutes, seconds];

hours minutes seconds to seconds ios

I want to convert time hours minutes seconds to seconds in ios.
Is there any in built method for this?
How can I do this?
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDiff = [gregorianCalendar components:NSHourCalendarUnit fromDate:[NSDate date]];
Following code for the insert date as a string and then return numbers of second.
- (NSNumber *)dateToSecondConvert:(NSString *)string {
NSArray *components = [string componentsSeparatedByString:#":"];
NSInteger hours = [[components objectAtIndex:0] integerValue];
NSInteger minutes = [[components objectAtIndex:1] integerValue];
NSInteger seconds = [[components objectAtIndex:2] integerValue];
return [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60) + seconds];
}
May this help to lot.
Maybe I misunderstand the question but this will give you current time in seconds from 1970
[[NSDate date] timeIntervalSince1970]
Plenty of examples, but this what you can do:
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [calendar components:NSHourCalendarUnit fromDate:now];
//[comp hour]
//[comp minute]
//[comp second]

Convert NSString to a Time, and then calculate "Time Until"

I have been on SO for awhile now trying to get this problem solved but have not had any luck.
In a nutshell I want to take a string like this: "2011-11-21 11:20:00" and calculate the "Time Until".
In a format like "1 day 36 mins" which would be a string I could display in a label.
I cant wrap my head around this. Anyone have some sample code from doing this before? Any help would be greatly appreciated.
#Maudicus is on the right track but has some flaws in his answer.
The date format you'd need to use is #"yyyy-MM-dd HH:mm:ss"
Once you have the date, you should use -[NSCalendar components:fromDate:toDate:options:] to figure out the differences between one date and another. For example:
NSDate *date = ...; // the date converted using the date formatter
NSDate *target = [NSDate date]; // now
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger components = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *difference = [calendar components:components fromDate:date toDate:target options:0];
NSLog(#"difference: %d days, %d hours, %d minutes, %d seconds", [difference days], [difference hours], [difference minutes], [difference seconds]);
This code should help you out.
NSDate * date;
//Assume dateString is populated and of format NSString * dateString =#"2011-11-21 11:20:00";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
//EDITED date formatter to correct behavior
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
if (dateString != nil) {
date = [dateFormatter dateFromString:dateString];
}
[dateFormatter release];
NSTimeInterval difference = [date timeIntervalSinceDate:[NSDate date]];
int days = difference/(3600*24);
difference -= (float) (days*3600*24);
int hours = difference/(3600);
difference -= (float) (hours*3600);
int minutes = difference/(60);
NSString * timeRemaining = [NSString stringWithFormat:#"%dd %dh %dm", days, hours, minutes];
duration.text = [NSString stringWithFormat:#"%d:%02d", (int)audioPlayer.duration / 3600, (int)audioPlayer.duration % 60, nil];

Check whether a specified date is today, yesterday, or a future date

I have one query regarding NSDate. I have a date i.e. "2011-10-04 07:36:38 +0000", and I want to check if this date is yesterday, or today or a future date.
How would I go about this?
Try this:
Note: Change the date format as per your need.
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSDate* enteredDate = [df dateFromString:#"10/04/2011"];
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:enteredDate];
switch (result)
{
case NSOrderedAscending:
NSLog(#"Future Date");
break;
case NSOrderedDescending:
NSLog(#"Earlier Date");
break;
case NSOrderedSame:
NSLog(#"Today/Null Date Passed"); //Not sure why This is case when null/wrong date is passed
break;
}
See Apple's documentation on date calculations:
NSDate *startDate = ...;
NSDate *endDate = ...;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
If days is between +1 and -1 then your date is a candidate for being "today". Obviously you'll need to think about how you handle hours. Presumably the easiest thing would be to set all dates to be 00:00.00 hours on the day in question (truncate the date using an approach like this), and then use those values for the calculation. That way you'd get 0 for today, -1 for yesterday, +1 for tomorrow, and any other value would likewise tell you how far things were in the future or the past.
Use any of the folowing according to ur need,
– earlierDate:
– laterDate:
– compare:
Refer this http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
-(NSString*)timeAgoFor:(NSString*)tipping_date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:tipping_date];
NSString *key = #"";
NSTimeInterval ti = [date timeIntervalSinceDate:[NSDate date]];
key = (ti > 0) ? #"Left" : #"Ago";
ti = ABS(ti);
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:date];
if (result == NSOrderedSame) {
return[NSString stringWithFormat:#"Today"];
}
else if (ti < 86400 * 2) {
return[NSString stringWithFormat:#"1 Day %#",key];
}else if (ti < 86400 * 7) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:#"%d Days %#", diff,key];
}else {
int diff = round(ti / (86400 * 7));
return[NSString stringWithFormat:#"%d Wks %#", diff,key];
}
}

How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

I have a time interval that spans years and I want all the time components from year down to seconds.
My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on.
That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method.
Is there?
I integrated Alex's 2nd method into my code.
It's in a method called by a UIDatePicker in my interface.
NSDate *now = [NSDate date];
NSDate *then = self.datePicker.date;
NSTimeInterval howLong = [now timeIntervalSinceDate:then];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong];
NSString *dateStr = [date description];
const char *dateStrPtr = [dateStr UTF8String];
int year, month, day, hour, minute, sec;
sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec);
year -= 1970;
NSLog(#"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec);
When I set the date picker to a date 1 year and 1 day in the past, I get:
1 years 1 months 1 days 16 hours 0
minutes 20 seconds
which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount.
Update: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?
Brief Description
Just another approach to complete the answer of JBRWilkinson but adding some code. It can also offers a solution to Alex Reynolds's comment.
Use NSCalendar method:
(NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts
"Returns, as an NSDateComponents object using specified components, the difference between two supplied dates". (From the API documentation).
Create 2 NSDate whose difference is the NSTimeInterval you want to break down. (If your NSTimeInterval comes from comparing 2 NSDate you don't need to do this step, and you don't even need the NSTimeInterval, just apply the dates to the NSCalendar method).
Get your quotes from NSDateComponents
Sample Code
// The time interval
NSTimeInterval theTimeInterval = ...;
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
// Get conversion to months, days, hours, minutes
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];
NSLog(#"Break down: %i min : %i hours : %i days : %i months", [breakdownInfo minute], [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]);
This code is aware of day light saving times and other possible nasty things.
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components: (NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit )
fromDate:startDate
toDate:[NSDate date]
options:0];
NSLog(#"%ld", [components year]);
NSLog(#"%ld", [components month]);
NSLog(#"%ld", [components day]);
NSLog(#"%ld", [components hour]);
NSLog(#"%ld", [components minute]);
NSLog(#"%ld", [components second]);
From iOS8 and above you can use NSDateComponentsFormatter
It has methods to convert time difference in user friendly formatted string.
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
NSLog(#"%#", [formatter stringFromTimeInterval:1623452]);
This gives the output - 2 weeks, 4 days, 18 hours, 57 minutes, 32 seconds
Convert your interval into an NSDate using +dateWithIntervalSince1970, get the date components out of that using NSCalendar's -componentsFromDate method.
SDK Reference
This works for me:
float *lenghInSeconds = 2345.234513;
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:lenghInSeconds];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
[formatter setDateFormat:#"HH:mm:ss"];
NSLog(#"%#", [formatter stringFromDate:date]);
[formatter release];
The main difference here is that you need to adjust for the timezone.
Or there is my class method. It doesn't handle years, but that could easily be addedn though it's better for small timelaps like days, hours and minutes. It take plurals into account and only shows what's needed:
+(NSString *)TimeRemainingUntilDate:(NSDate *)date {
NSTimeInterval interval = [date timeIntervalSinceNow];
NSString * timeRemaining = nil;
if (interval > 0) {
div_t d = div(interval, 86400);
int day = d.quot;
div_t h = div(d.rem, 3600);
int hour = h.quot;
div_t m = div(h.rem, 60);
int min = m.quot;
NSString * nbday = nil;
if(day > 1)
nbday = #"days";
else if(day == 1)
nbday = #"day";
else
nbday = #"";
NSString * nbhour = nil;
if(hour > 1)
nbhour = #"hours";
else if (hour == 1)
nbhour = #"hour";
else
nbhour = #"";
NSString * nbmin = nil;
if(min > 1)
nbmin = #"mins";
else
nbmin = #"min";
timeRemaining = [NSString stringWithFormat:#"%#%# %#%# %#%#",day ? [NSNumber numberWithInt:day] : #"",nbday,hour ? [NSNumber numberWithInt:hour] : #"",nbhour,min ? [NSNumber numberWithInt:min] : #"00",nbmin];
}
else
timeRemaining = #"Over";
return timeRemaining;
}
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// format: YYYY-MM-DD HH:MM:SS ±HHMM
NSString *dateStr = [date description];
NSRange range;
// year
range.location = 0;
range.length = 4;
NSString *yearStr = [dateStr substringWithRange:range];
int year = [yearStr intValue] - 1970;
// month
range.location = 5;
range.length = 2;
NSString *monthStr = [dateStr substringWithRange:range];
int month = [monthStr intValue];
// day, etc.
...
- (NSString *)convertTimeFromSeconds:(NSString *)seconds {
// Return variable.
NSString *result = #"";
// Int variables for calculation.
int secs = [seconds intValue];
int tempHour = 0;
int tempMinute = 0;
int tempSecond = 0;
NSString *hour = #"";
NSString *minute = #"";
NSString *second = #"";
// Convert the seconds to hours, minutes and seconds.
tempHour = secs / 3600;
tempMinute = secs / 60 - tempHour * 60;
tempSecond = secs - (tempHour * 3600 + tempMinute * 60);
hour = [[NSNumber numberWithInt:tempHour] stringValue];
minute = [[NSNumber numberWithInt:tempMinute] stringValue];
second = [[NSNumber numberWithInt:tempSecond] stringValue];
// Make time look like 00:00:00 and not 0:0:0
if (tempHour < 10) {
hour = [#"0" stringByAppendingString:hour];
}
if (tempMinute < 10) {
minute = [#"0" stringByAppendingString:minute];
}
if (tempSecond < 10) {
second = [#"0" stringByAppendingString:second];
}
if (tempHour == 0) {
NSLog(#"Result of Time Conversion: %#:%#", minute, second);
result = [NSString stringWithFormat:#"%#:%#", minute, second];
} else {
NSLog(#"Result of Time Conversion: %#:%#:%#", hour, minute, second);
result = [NSString stringWithFormat:#"%#:%#:%#",hour, minute, second];
}
return result;
}
Here's another possibility, somewhat cleaner:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSString *dateStr = [date description];
const char *dateStrPtr = [dateStr UTF8String];
// format: YYYY-MM-DD HH:MM:SS ±HHMM
int year, month, day, hour, minutes, seconds;
sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minutes, &seconds);
year -= 1970;