How to calculate different between two NSDate variable? - objective-c

I am building an IOS application where I am doing following step.
Parsing the data.
Getting OpenTime and CloseTime.
Set the OpenTime and CloseTime in a NSString variable name as openTime and closeTime.
Now the problem is I want to calculate the different of this two time.
I am getting the value like,
OpenTime = "00:15:00" and CloseTime = "1:30:00"
The Time formate is - 24 hours.
Can someone help me in solving this problem I am new in IOS.

Let say you have two NSDate variables openTime and closeTime
int calendarUnit = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:calendarUnit fromDate: openTime toDate: closeTime options:0];
int months = [components month];
int days = [components day];
int hours = [components hour];
int minutes = [components minute];

You can use NSDateComponents
NSDate *date = [self getTimeInDateFormatFromString://your time string]; // your method return nsdate from string using nsformatter
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comp = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
you can use comp.hour and minute to get time difference.

NSString *openTime = #"12:48:00";
NSString *closingTime = #"21:52:00";
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"hh:mm:ss"];
NSDate *openDate = [formatter dateFromString:openTime];
NSDate *closeDate = [formatter dateFromString:closingTime];
int calendarUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [[NSCalendar currentCalendar] components:calendarUnits fromDate: openDate toDate: closeDate options:0];
NSLog(#"The difference is: %ld hours , %ld minutes, %ld seconds", (long)components.hour, (long)components.minute, (long)components.second);

-(void)compareTwoDate:(NSDate *)start :(NSDate *)end
{
NSDate *end_date =end;
NSDate *startDate =start;
NSTimeInterval distanceBetweenDates = [startDate timeIntervalSinceDate:end_date];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
}

NSArray *star_array=[#"00:15:00" componentsSeparatedByString:#":"];
NSInteger start_time=[[star_array objectAtIndex:2] integerValue]*3600+[[star_array objectAtIndex:1] integerValue]*60+[[star_array objectAtIndex:0] integerValue];
NSArray *end_array=[#"1:30:00" componentsSeparatedByString:#":"];
NSInteger end_time=[[end_array objectAtIndex:2] integerValue]*3600+[[end_array objectAtIndex:1] integerValue]*60+[[end_array objectAtIndex:0] integerValue];
NSInteger diff_seconds=end_time-start_time;

Related

Syntax error in date calculation

I am using following code in Xcode:
(void)updateLabel
{
NSDate* now = [NSDate date];
int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay];
int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour];
int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute];
countdownLabel.text = [NSString stringWithFormat:#"%02d:%02d:%02d", hour, min,sec];
}
And am getting the following error. How can I fix this?
error: invalid operands to binary - (have 'int' and 'id')
You must be using this way :-
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
Hope it helps you
Use this way
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
long hour =23-[dateComponents hour];
long min =59-[dateComponents minute];
long sec =59-[dateComponents second];
NSString *str = [NSString stringWithFormat:#"%02ld:%02ld:%02ld", hour, min,sec];
NSLog(#"--> %#",str);

Create a NSDate with a user selected time in objective c

int hour = [[array objectAtIndex:0] intValue]; //hour = 17
int min = [[array objectAtIndex:1] intValue]; //min = 51
NSLog(#"hour value is %d",hour);
NSLog(#"min value is %d",min);
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
int year = [components year];
int month = [components month];
int day = [components day];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.timeStyle = NSDateFormatterNoStyle;
[components setYear:year];
[components setMonth:month];
[components setDay:day];
[components setHour:hour];
[components setMinute:min];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
NSDate *itemDate = [cal dateFromComponents:components];
NSLog(#"the date is %#",itemDate);
Output:
the date is 2012-11-03 01:00:00 +0000 . But i want the output to be 2012-11-03 17:51:00..how can i get it?What am i doing wrong?
It appears your issue is a simple matter of not realizing that the NSDate object will be created using your own current timezone but the NSLog will print out the NSDate description using UTC. Since you appear to be in PDT (it will be PST later this weekend when the clocks change in the USA), your NSLog should show the desired date/time but it will appear to be 7 hours (8 hours later this weekend) off.
To show your date in the local timezone, use an NSDateFormatter to convert the NSDate to an NSString.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"the date is %#", dateString);

Breaking Up a String in Objective-C

All,
I have a method that takes a date (YYYY-MM-DD H:M:S) from the database and creates a URL with the year, month and day components from the date string. My solution works but I was wondering if there is a better way to do this? How are the cool kids doing it? :-)
Thanks!
-(NSString *) prettyURLFrom:(NSString *)dateString{
NSString * URLString = #"";
NSString *URL = #"http://www.theblues.com/featured/article/";
NSArray *myWords = [dateString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"-\" \" :"]
];
URLString = [NSString stringWithFormat:#"%#%#/%#/%#",
URL,
[myWords objectAtIndex:1],
[myWords objectAtIndex:2],
[myWords objectAtIndex:0]];
return URLString;
}
Like I said in the comments, I find it bizarre you're passing and returning values as strings when they probably should be NSDate and NSURL respectively.
I would probably do something like:
-(NSURL*)URLFromDate:(NSDate*)date
{
// Assumes user uses a gregorian calendar
NSDateComponents *dateComp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
return [NSURL URLWithString:[NSString stringWithFormat:#"http://www.theblues.com/featured/article/%li/%li/%li"
, [dateComp year]
, [dateComp month]
, [dateComp day]]];
}
If you have NSDate object then you can use
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSString to NSDate
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-DD HH:MM:SS"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:#"1999-07-02 2:2:4"];

Getting current time

I'm trying to get current hour minutes and seconds. Here is the code I use
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
[self.timerLabel setText:[NSString stringWithFormat:#"%# %# %#", [dateComponents hour], [dateComponents minute], [dateComponents second]]];
When I run the app crash on the line where self.timerLabel is.
What is wrong here ?
When i run the code it works fine here.
what's the following line in your code ? Are you sure that it crashes on the third line in the code you pasted ? maybe the code you pasted is not the same than the one in your xcode.
Edit : it's because you're using %# in your string which belongs to UTF-8 string. [dateComponents hour] etc. are returning NSInteger, so you should use %d instead.
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger hour= [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
Just doing
NSDate *datenow = [NSDate date];
you will have the current date and time, to generate string representations of a date, you should use an instance of NSDateFormatter.

how to get iphone time

can you help out in finding the iphone time through iphone application
NSDate *today = [NSDate date];
Gives you the current time and date.
NSDate *today = [NSDate date];
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:today];
[calendar release];
NSInteger hour = [dateComponents hour];
NSInteger min = [dateComponents minute];
NSInteger sec = [dateComponents second];
This will actually get just the time from the date, not the whole date. It gets the time in separate integers, hour, min, sec. To put them all back together in a string you can do the following:
NSString *time = [NSString stringWithFormat:#"%i:%i:%i", hour, min, sec];