Reputation: 5175
My class needs two properties: startTime
and endTime
. What is the best class to use? I know there is NSDate, but I only need to store a specific time (something in between 00:00-23:59), I don't need a date. What is the most elegant solution here?
Upvotes: 1
Views: 278
Reputation: 36752
I believe the most elegant solution, and what you want, is NSTimeInterval
, that is the primitive type that NSDate
is built on top.
NSTimeInterval
is a typedef for double
, and is a measurement of time in seconds. This primitive time type do not have any concept of a reference date. What NSDate
do is to add this concept of reference date and anchor the 0.0 time at 1 January 2001 GMT. There is nothing that stops you from inventing your own reference date or anchor, like for example "midnight of whatever day there is".
What you can do is to add two properties of the NSTimeInterval
either as startTime
and endTime
and let them both use midnight as the reference. Or you could skip endTime
and go for a startTime
and duration
combo.
Upvotes: 1
Reputation: 55334
The NSDate
class is similar to the DateTime
class in C#: both hold a date and time, but they can be independent of each other. In Cocoa, you would compare two NSDate classes:
//Create NSDate objects in the time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *startTimeString = @"00:00:00"; //0 seconds
NSString *endTimeString = @"00:00:52"; //52 seconds
NSDate *startTime = [dateFormatter dateFromString:startTimeString];
NSDate *endTime = [dateFormatter dateFromString:endTimeString];
//Compare the time
BOOL date1before2 = [startTime compare:endTime] == NSOrderedAscending;
Upvotes: 0
Reputation: 58448
NSTimeInterval is probably good enough for this.
It stores a time value in seconds as a double.
Eg. 5 mins = 300.0
Upvotes: 3
Reputation:
There's NSDateComponents
, which "can also be used to specify a duration of time, for example, 5 hours and 16 minutes."
Upvotes: 0