Reputation: 9850
I have a String with the time as follows;
NSString *time = "06.45 pm";
I need to assume that this time is on today's date and then get the current System time, and calculate the time difference between the two.
How can i do this ?
Note: The above time doesn't specify a date
, (Only the time is given)
Upvotes: 1
Views: 7516
Reputation: 25740
Make sure that when you do this that you are using calendar operations so that it takes into account time changes (daylight savings time, leap seconds, etc.):
NSString *time = @"06.45 pm";
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh.mm a"];
// Convert time to a NSDate and break it down into hours, minutes, and seconds:
NSDate *timeAsDate = [formatter dateFromString:time];
NSDateComponents *timeComps = [cal components:NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit
fromDate:timeAsDate];
// Take today's date and add "time" to it:
NSDateComponents *comps = [cal components:NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit
fromDate:today];
comps.hour = timeComps.hour;
comps.minute = timeComps.minute;
comps.second = timeComps.second;
NSDate *timeOnTodaysDate = [cal dateFromComponents:comps];
// Now calculate the difference:
NSTimeInterval difference = [today timeIntervalSinceDate:timeOnTodaysDate];
Upvotes: 2
Reputation: 2968
NSString *time = @"06.45 pm";
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh.mm a"];
date1 = [formatter dateFromString:time];
date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
[formatter release];
}
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));
Upvotes: 3