Time difference between two times in iPhone - iphone

I have two times :
10:23:51
10:31:54
Both values are stored as strings in a SQLite database.
I want to find the difference between these two times in hh:mm format.
How can I do this?
I have searched a lot. But can't find a proper solution.
Help me out.
Thanks.
Edit :
See basically I am having two arrays:
InTimeArray and OuttimeArray.
Now in the viewDidload method , I am fetching all the intime entries in the IntimeArray and Outtime entries in the outtime Arrays.
Now I am passing one by one values in tableview like in 1st row
IntimeArray[0]
OuyTimeArray[0]
second row:
IntimeArray[1]
OuyTimeArray[1]
Now I want to count the differences between 1st row's intime and outtime in HH:MM format.
I am really confused.

you can take a look at that :
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [dateFormat dateFromString:string];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
this will turn the NSDate to you and when you change them both to NSDates then you can learn the difference by looking at this.
i hope this will help you..

You have to first change your both strings into date format using this method :-
- (NSDate *)dateFromString:(NSString *)string;
after that you just have to calculate number of seconds between both the dates.Thats it.
OR there is another simple way to do this. i.e.
get dates from both arrays first like this:-
NSDate *eventStartDate = [IntimeArray objectAtIndex:indexpath.row];
NSDate *eventEndDate = [OuyTimeArray objectAtIndex:indexpath.row];
Then calculate difference between both the dates like this :-
NSTimeInterval startTimeInterval = [eventStartDate timeIntervalSinceDate:currentDate];
Hope it helps Thanks :)

Try this:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *d1 = [formatter dateFromString:IntimeArray[0]];
NSDate *d2 = [formatter dateFromString:OuyTimeArray[0]];
NSTimeInterval ti = [d2 timeIntervalSinceDate:d1];
float hours = floor(ti / 3600);
float minutes = floor((ti - hours*3600) / 60);
NSString *s = [NSString stringWithFormat:#"%02.0f:%02.0f",hours,minutes];
For your given example, NSLog(#"Time passed: %#",s); will print 00:08.

Related

NSdateFormatter in iphone sdk

I am beginner in ios development.
I am stuck in NSdateFormatter class.
My question is:
Which kind of formatter support on this date "Oct, 25th"?
Please help me,
Thanks in advance...
you can format date by "Oct, 25" you must append "th" with the formatted date
I would like te stress you not to use explicit date formats, since if the users setting is not set to english the date might not be presented correctly.
Instead you should use the dateStyle and timeStyle properties of NSDateFormatter.
See Apple NSDateFormatterStyle documentation to see which one will work for you.
[yourDateFormatter setDateFormat:#"LLL,dd'th'"];
LLL: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
dd: 01~31 ( Day of Month)
for more info about date-formate see my blog from this link..
MyBlog
For Example
call this method with bellow 2 line code..
NSString *strDate = [self StringFromDate:#"Oct, 25th"];
NSLog(#"\n New Date is HERE =====>> %#",strDate);
this is the method just paste in your .m file
-(NSString *)StringFromDate:(NSString *)DateLocal{
// DateLocal = [self trimString:DateLocal];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"LLL,dd'th'"];
NSDate *date = [dateFormatter dateFromString: DateLocal];
NSString *tt = [dateFormatter stringFromDate:date];
NSDate *dateReturn = [dateFormatter dateFromString:tt];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd,LLL"];// set the format which you want
NSString *dateString = [dateFormat stringFromDate:dateReturn];
NSLog(#"Date is HERE =====>> %#",dateString);
[dateFormat release];
return dateString;
}

Time zone added to hour after using nsdateformatter

I'm trying to convert a string date (2011-06-08T08:05:00.000-08:00) into a NSDate using the following code:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//Translate 2011-06-08T08:05:00.000-08:00 into 2011-06-08T08:05:00.000-0800
stringDate = [stringDate stringByReplacingOccurrencesOfString:#":" withString:#"" options:0 range:NSMakeRange([aDate length] - 5, 5)];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZ"];
NSDate *dateFromString = [dateFormatter dateFromString:stringDate];
At this point, dateFromString is 2011-06-08 16:05:00 +0000. What I actually wanted was for dateFromString to be 2011-06-08 08:05:00 -0800. What am I doing wrong?
Thanks!
So this will not have a direct answer and will assume that your string format will be the same. What we are going to extract the timezone part (last 5 characters) and then calculate how many seconds we are off from GMT. NSTimeZone has a convenience method timeZoneForSecondsFromGMT: that will help us get what we need. This is what you need to add to the code in the question.
NSString * zoneString = [stringDate substringFromIndex:([stringDate length] - 5)];
NSTimeInterval timeInterval = [[zoneString substringToIndex:3] intValue] * 3600;
timeInterval += [[zoneString substringFromIndex:3] intValue] * 60;
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:timeInterval]];
[formatter setDateFormat:#"yyyy'-'MM'-'dd' 'HH':'mm':'ss ZZZ"];
NSLog(#"%#", [formatter stringFromDate:dateFromString]);
Hopefully this helps you. If you've found a better answer already, let us know.
Original Answer
One thing about the NSDate is that the time returned is always in GMT. You can't change that. You will have to use an NSDateFormatter to print it right. Something like this,
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"PST"]];
[formatter setTimeStyle:NSDateFormatterFullStyle];
[formatter setDateStyle:NSDateFormatterFullStyle];
NSLog(#"%#", [formatter stringFromDate:[NSDate date]]);
So setting the timezone for the formatter that does dateForString: won't help. You will need to create a new one when you want them with a different timezone.

Converting NSStrings in an array into NSDates

I'm working on an assignment that allows the user to display events that are happening 'today'. I have parsed the XML file and stored the contents into an array. The contents of the XML file consists of a title, description, date etc. The dates are in NSString format and I want to convert them into NSDates and compare them with today's date before displaying them in a UITableView.
I'm new to obj-c and I've searched online for help on NSDate, but I couldn't find what I need. Any links, advice or help on this is really appreciated. Thanks in advance (:
suppose dateString contains the date in string format
first get date from string:-
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/mm/yyyy"];
NSDate *dateprevious = [formatter dateFromString:dateString];
Now get today date
NSDate *date=[NSDate date];
[formatter setDateFormat:#"dd"];
NSString *dateOfGame =[formatter stringFromDate:dateprevious];
NSString *todaydate =[formatter stringFromDate:date];
[formatter release];
if([todaydate isEqualToString:dateknown])
{
NSLog(#"date matched");
}
Depending on the format of the string, you can use this:
+ (id)dateWithNaturalLanguageString:(NSString *)string
To compare two dates you will find here a lot of usefull answers :)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy , hh:mm a"];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSDate *date = [[dateFormatter datefromString:date] retain];
[dateFormatter release];
You can use this one
Have a look at NSDateFormatter
It has a method called dateFromString
Like you could do the following:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/mm/yyyy"];
NSDate *date = [formatter dateFromString:#"5/5/2011"];

How to compare just dates not the time?

How can I compare the dates only, not the time. I am using
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *tempDate = #"2-2-2012"; //Dynamic Date
NSDate *dateString = [dateFormatter dateFromString:tempDate];
NSLog(#"%#",dateString);
It logs this: 2012-02-01 18:30:00 +0000
NSDate *now = [NSDate date];//Current Date
NSLog(#"%#",now);
It logs this: 2011-04-04 14:49:45 +0000
I want to compare Dynamic date and current date, I don't need time. I may not using the correct NSDateFormatter. Can anyone of you tell me how to do this? If I am not clear, please let me know.
Suppose I have to strings
date1 = 3-2-2011;
date2 = 4-5-2020;
I want to convert them in date, only after that I can compare them. Its not happening from my date Formatter. Please have a look.
Thanks!
Simplest way is to compare date by converting it into string.
Sample Code is as shown below:
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];
//Other Date say date2 is of type NSDate again
NSString *date2String = [formatter stringFromDate:date2];
//Comparison of Two dates by its conversion into string as below
if([date2String isEqualToString:dateString])
{
//Your logic if dates are Equal
}
else if(![date2String isEqualToString:dateString])
{
//Your Logic if dates are Different
}
EDIT:
Checkout this link.
Comparing dates
http://www.iphonedevsdk.com/forum/iphone-sdk-development/64625-how-compare-2-dates.html
Hope This Helps You. :)
Use NSCalendar and NSDateComponents to get a date components object. Then you can look at only those parts of the date that you care about.
If you're just trying to determine whether two dates are the same, regardless of time, one way to go is to use NSDate's -timeIntervalSinceDate: method. If the time interval returned is less than 86,400 seconds (i.e. 24 hours * 60 minutes * 60 seconds) then you can feel fairly sure that it's the same day. Changes related to such things as daylight savings time and leap seconds introduce some possibility of error... if that's a problem, go with NSDateComponents.
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLocale:[NSLocale autoupdatingCurrentLocale]];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];

How can I convert a NSString representation of a time value into two NSInteger's containing the hour and minute?

I'm diving into iOS development and the Objective C language and am building an alarm clock app to become familiar with the SDK and language. I have an NSString object that represents a time, with the range "1:00 am" to "12:59 am". I need to convert this NSString into two NSInteger's that contain the hour value and minute value. As I'm doing this, I'm finding the NSString manipulation that I'm doing to be extremely laborious and it just feels like sloppy code.
Is there a simple way to extract the hour and minute characters from a NSString representation of a time value and store their numerical values in two NSInteger's?
Thanks in advance for all your help! I'm gonna get back to it...
NSScanner* timeScanner=[NSScanner scannerWithString:...the time string...];
int hours,minutes;
[timeScanner scanInt:&hours];
[timeScanner scanString:#":" intoString:nil]; //jump over :
[timeScanner scanInt:&minutes];
NSLog(#"hours:%d minutes:%d",hours,minutes);
Use an NSDateFormatter to convert your string into an NSDate.
Use the [NSCalendar currentCalendar] to extract various date components (like the hour, minute, etc).
In other words:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:m a"];
NSDate *date = [formatter dateFromString:#"12:59 pm"];
[formatter release];
NSDateComponents * components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSLog(#"hour: %d", [components hour]);
NSLog(#"minute: %d", [components minute]);
This is the official way, as I know it. It's not pretty:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
[dateFormatter setDateFormat:#"h:m a"];
NSDate *date = [dateFormatter dateFromString:#"12:34 am"];
[dateFormatter setDateFormat:#"h"];
NSString *hours = [dateFormatter stringFromDate:date];
[dateFormatter setDateFormat:#"m"];
NSString *minutes = [dateFormatter stringFromDate:date];
BUT the string fiddling way of doing it (look for :, look for space, ...), may give you more headaches on the long term.
NSString *time = #"1:00 am";
NSString *removeam = [time stringByReplacingOccurencesOfString:#" am" withString:#""];
SString *removepm = [removeam stringByReplacingOccurencesOfString:#" pm" withString:#""];
NSArray *timeArray = [removepm componentsSeparatedByString:#":"];
NSInteger *hour = [[timeArray objectAtIndex:0] intValue];
NSInteger *mins = [[timeArray objectAtIndex:1] intValue];
If you're building an alarm clock app, you probably will want to look into the NSDate and NSDateFormatter classes, instead of trying to pull all those strings apart into integer types. Also, your time range is a bit weird (maybe a typo?) - don't you want all 24 hours to be available?
get the time interval and write it as
duration.text = [NSString stringWithFormat:#"%d:%02d", (int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60, nil];