My problem is I want to have some way to represent time (without date), like time of day in my iOS app. From a REST api I get strings like "13:12:11" which shows the time something happens, I have used NSDateFormatter
to convert NSStrings to NSDates but as far as I can tell it does not accept date formats with just time components like HH:mm:ss
[EDIT: you can, see below]
So my questions are
1- Is NSTimeInterval (instead of NSDate) what I should be using to store time of day?
2- How can I convert "03:04:05" to and objective-c object from one of the built in frameworks.
EDIT: You CAN use formats like "HH:mm:ss" it just replaces the date part with 2000-01-01 Still it would be very nice to have a date independent time of day representation.
OK, thanks everybody, this is what I ended up doing:
NSString * timeAsString = "12:26:07";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSDate * dateZero = [dateFormatter dateFromString:@"00:00:00"];
NSDate * dc = [dateFormatter dateFromString:timeAsString];
NSTimeInterval startTime = [dc timeIntervalSinceDate:dateZero];
It is not an elegant solution but it works, at least for what I need to do,
You can use NSDateComponent to create dates based on a time. You can add values to the year based on the current date or a future/past date.
NSDateComponents *component=[[NSDateComponents alloc] init];
[component setHour:yourHour];
[component setMinute:yourMinutes];
[component setYear:yourYear];
[component setMonth:yourMonth];
[component setDay:yourDaty];
NSCalendar *calendar=[NSCalendar currentCalendar];
NSDate *date=[calendar dateFromComponents:component];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With