'How do I obtain the sub-second portion of an NSDate?

Using OS X v10.10.1 (Yosemite) and Xcode 6.1.1.

I feel I must be overlooking something simple and obvious, but I just can't see it. I'm parsing the parts of an NSDate whose value is just the system date.

NSDate *currentDate = [NSDate date];
NSCalendar *systemCalendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [systemCalendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:currentSystemDate];

I can then get the seconds as

NSInteger seconds = [dateComponents second];

but this only gives me the whole number of seconds. I need the decimal portion of the seconds as well. According to the documentation. I can use

NSInteger nanos = [dateComponents nanoseconds];

to get the "number of nanosecond units for the receiver". It doesn't work however. The method is legitimate, but nanos is set to the maximum value of NSInteger. This is (I presume) because I have not supplied a suitable constant in the components method. The problem with that is that there is no NSNanosecondCalendarUnit constant and I cannot find any suitable alternative.

I could construct a new date using the date components and then subtract the two to get an NSTimeInterval which I believe will give me what I need, but I'm finding it hard to believe that there isn't a more straightforward way to get it.

Is there a simple straightforward way in Cocoa to calculate the sub-second portion of an NSDate or do I have to use the approach I just suggested?



Solution 1:[1]

You are using the older deprecated names for the components. The new names include NSCalendarUnitNanosecond. Take a look at NSCalendar.h, and you'll see the old and new names.

NSDateComponents *dateComponents = [systemCalendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitNanosecond) fromDate:currentSystemDate];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen