Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate but no NSTime , how to convert a string representation of time (without date)

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.

like image 260
Ali Avatar asked Dec 27 '22 17:12

Ali


2 Answers

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,

like image 117
Ali Avatar answered May 07 '23 21:05

Ali


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];
like image 31
J2theC Avatar answered May 07 '23 22:05

J2theC