how to calculate difference between two times in different dates in iOS? - ios

starttime= 23:00 pm
end time= 5:00 am
I need the summing time of the start time to end time
i am trying this code but it is not helpful to me
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"HH"];
NSDate *currentTime = [NSDate date];
NSDate *openTime = [formatter dateFromString:start];
NSDate *closeTime = [formatter dateFromString:end ];
NSCalendar *calender = [NSCalendar currentCalendar];
NSDateComponents *currentTimeComponents = [calender components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:currentTime];
NSDateComponents *openTimeComponents = [calender components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:openTime];
NSDateComponents *closeTimeComponents = [calender components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:closeTime];
NSUInteger currentTimeSeconds = currentTimeComponents.hour;
NSUInteger openTimeSeconds = openTimeComponents.hour;
NSUInteger closeTimeSeconds = closeTimeComponents.hour;
if (currentTimeSeconds>openTimeSeconds && currentTimeSeconds<closeTimeSeconds) {
NSLog(#"Time Between Open and Close Time %lu",(unsigned long)currentTimeSeconds);
}
and it shows 0 hors.
please help me some one?
thanks in advance

If possible, I'd look at using libs/frameworks to accomplish that through their APIs. For example, I've done date operations using DateTools

Related

Get time from pressed button (hold pressed)

When trying to get the time, I am not getting the expected value.
When I ran this, the time was 19:59. And in the timeDifferenceString, the Value was 71976.894206.
I think that this is the current time.
I calculate 71976 / 3600 = 19,99 h
0,99 * 60 = 59,4 m
0,4 * 60 = 24 s
So I get the time 19:59:24 o'clock. But I want get the difference between the first time and the second time and not the current time in seconds.
I want only get the time when I (hold) pressed the button
and the time that the button is not pressed (by starting the first time if I press on the button and stopped if I press on an other button).
- (IBAction)pressTheButton:(id)sender {
NSDate * now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss:SSS"];
NSString *currentTime = [formatter stringFromDate:now];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components; //= [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:10];
NSDate* firstDate = [NSDate date];
NSString *getTime = [formatter stringFromDate:now];
getTime = [formatter stringFromDate:firstDate];
if (iX==0)
{
components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
firstDate = [calendar dateFromComponents:components];
getTime = [formatter stringFromDate:firstDate];
//firstDate = [NSDate date];//[dateFormatter dateFromString:#"00:01:00:090"];
}
components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
//NSDate* secondDate = [dateFormatter dateFromString:#"10:01:02:007"];
NSDate * secondDate = [calendar dateFromComponents:components];
getTime = [formatter stringFromDate:firstDate];
NSTimeInterval timeDifference = [firstDate timeIntervalSinceDate:secondDate];
NSString *timeDifferenceString = [NSString stringWithFormat:#"%f", timeDifference];
timeDiff[iX] = [timeDifferenceString intValue];
[timeLabel setText:timeDifferenceString];
iX++;
}
If you have a better solution for my problem pleas help me.
Look at UIControlEventTouchDown, UIControlEventTouchUpInside here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIControl_Class/Reference/Reference.html
Then I suppose you want to store an NSDate of when you pressed down in some sort of ivar or property (UIControlEventTouchDown) and another one when you release the button (UIControlEventTouchUpInside or UIControlEventTouchUpOutside) and then call -timeIntervalSinceDate: on that date. So it would look roughly like this:
- (IBAction)pressedDown:(id)sender {
self.pressedDownDate = [NSDate date];
}
- (IBAction)touchedUp:(id)sender {
NSDate *now = [NSDate date];
NSLog(#"Time passed: %d", [now timeIntervalSinceDate:self.pressedDownDate]);
}

Get weeks date in IOS SDK

I want to get the current & next week dates with day name.
i.e. If today's date is 28-06-2013 (Friday) then I want to get the dates from 23-06-2013(sunday) to 29-06-2013 (Saturday) as the this current week.
for next week
I want to get dates from 30-06-2013(sunday) to 06-07-2013 (saturday).
How can I do this?
Thank you,
Here is sample code that does the trick.
-(NSArray*)daysThisWeek
{
return [self daysInWeek:0 fromDate:[NSDate date]];
}
-(NSArray*)daysNextWeek
{
return [self daysInWeek:1 fromDate:[NSDate date]];
}
-(NSArray*)daysInWeek:(int)weekOffset fromDate:(NSDate*)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
//ask for current week
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps=[calendar components:NSWeekCalendarUnit|NSYearCalendarUnit fromDate:date];
//create date on week start
NSDate* weekstart=[calendar dateFromComponents:comps];
if (weekOffset>0) {
NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];
moveWeeks.week=1;
weekstart=[calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0];
}
//add 7 days
NSMutableArray* week=[NSMutableArray arrayWithCapacity:7];
for (int i=1; i<=7; i++) {
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
compsToAdd.day=i;
NSDate *nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0];
[week addObject:nextDate];
}
return [NSArray arrayWithArray:week];
}
I was going to copy and paste an answer, but I'd suggest going and reading this post: Current Week Start and End Date. It looks like it'll help you achieve what you want to.
Something like this perhaps:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber = [[calendar components: NSWeekCalendarUnit fromDate:now] week];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
[comp setWeek:weekNumber]; //Week number.
int i;
for (i = 1; i < 8; i=i+1){
[comp setWeekday:i]; //First day of the week. Change it to 7 to get the last date of the week
NSDate *resultDate = [gregorian dateFromComponents:comp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE MMMM d, yyyy"];
NSString *myDateString = [formatter stringFromDate:resultDate];
NSLog(#"%#",myDateString);
}
Use NSDateComponents to find out the day of the week and then to find the date required before and after it.
Umm, I'm not an expert on this or anything, but a dumb way to do this is to first be able to recognize the day of the week from NSDate. Then you could add in if statements then the if statements could add and subtract the dates and nslog or printf each of them. Or I think there is a way by accessing the ios calendar.
okay so the above pretty much said and did more than what I said. Yeah go check the link on the post before me.
Use an NSCalendar instance to convert your start NSDate instance into an NSDateComponents instance, add 1 day to the NSDateComponents and use the NSCalendar to convert that back to an NSDate instance. Repeat the last two steps until you reach your end date.
NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
NSDate *nextDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
Or else find start date and end date. like
NSDate *startDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:7];
NSDate *endDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
then,
NSDate nextDate;
for ( nextDate = startDate ; [nextDate compare:endDate] < 0 ; nextDate = [nextDate addTimeInterval:24*60*60] ) {
// use date
}

UITableview title bar with date for week?

How can I have the title of UITableview with date?
I know I can edit the title using:
self.title=#"meals for ..";
I want to add the date for one week. How can I do that?
You can get a date like this:
NSDate *theDateToday = [NSDate date];
And format it like this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE MMM dd"];
NSString *theDateAsAString = [dateFormatter stringFromDate:theDateToday];
Combine that with what you have like this:
self.title = [NSString stringWithFormat:#"meals for %#", theDateAsAString];
As for finding the days of the week, you could try adapting this answer.
- (NSString *)getWeekStartDateAsString:(NSDate *)date {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"yyyy-MM-dd"];
dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];
return weekstartPrev;
}
- (NSString *)getWeekEndDateAsString:(NSDate *)date {
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:#"yyyy-MM-dd"];
dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];
return weekEndPrev;
}
You end result might look like this:
self.title = [NSString stringWithFormat:#"meals for %#-%#", [self getWeekStartDateAsString:theDateToday], [self getWeekEndDateAsString:theDateToday]];
A rarely known NSCalendar method will be the best option IMO
rangeOfUnit:startDate:interval:forDate:. It gives you the start and the duration (interval) for a certain time unit. With it it is easy to find the start of the week in the used calendar and add the range-1 to get the latest second in that week.
With the also rarely seen localizedStringFromDate:dateStyle:timeStyle: Available in OS X v10.6, iOS 4.0 it is easy to create a localized representation of the dates.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfWeek is 2013-06-02 22:00:00 +0000 now (note: it is GMT with timezone support for my timezone Europe/Berlin/DST)
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
// 2013-06-09 21:59:59 +0000
NSString *text = [NSDateFormatter localizedStringFromDate:startOfTheWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle];
text = [text stringByAppendingString:#" to "];
text = [text stringByAppendingFormat:#"%#", [NSDateFormatter localizedStringFromDate:endOfWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle]];
self.title=text;
results in 03.06.13 to 09.06.13 for my german locale, where Monday is start of the week.

NSDate subtracting trouble

so in my app I want to subtract two dates. The first date is set date and the second one is the current date. So i tried this code:
NSString *setDateString = [NSString stringWithFormat:#"12:30"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *setDate = [dateFormatter dateFromString:setDateString];
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:setDate];
But it counts the interval from 1970. But I need from the current day. Can anyone help?
I assume you want the difference between now and 1230 hrs of today. This can be done by
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =[gregorian components:(NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit) fromDate:today];
[components setHour:12];
[components setMinute:30];
[components setSecond:0];
NSDate *setDate=[gregorian dateFromComponents:components];
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:setDate];
[gregorian release];
The reason it doesn't work for you is you've not given the format correctly. Alternatively, you can describe it correctly in setDateString by specifying all the components rather than just hour and minute.

Showing "past" and "upcoming" sections UITableView with FetchedResultsController

I'm having a bit of difficulty grouping my table view by past and upcoming. This would be determined by a date field in my Core Data model. So all items with a date > today would be upcoming, and all with a date < today would be considered past. Any insight into this would be greatly appreciated.
You can use this function in your entities class:
-(NSString*)dateToStringForSectionTitels{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *formattedDateString;
[dateFormatter locale];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:components];
components = [cal components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:self.startDate];
NSDate *otherDate = [cal dateFromComponents:components];
if([today isEqualToDate:otherDate]) {
formattedDateString = #"Today";
}else{
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
formattedDateString = [dateFormatter stringFromDate:self.startDate];
}
NSTimeInterval distanceBetweenDates = [self.startDate timeIntervalSinceDate:[NSDate date]];
double secondsInAnMinute = 60;
NSInteger minutsBetweenDates = distanceBetweenDates / secondsInAnMinute;
if (minutsBetweenDates<30) {
formattedDateString = #"Starting Soon";
}else if(minutsBetweenDates<0){
formattedDateString = #"In the past";
}
return formattedDateString;
}
It will return
The date in a string if the event is in the future
"Today" if the event is today.
"Starting soon" if the event is starting in 30 minutes - (You can range it to what ever you wish.
"In the past" if the event is in the past.
Then just pass the "dateToStringForSectionTitels" to your fetch result controller.
Good luck.

Resources