Search code examples
iosobjective-ciphonenstimeinterval

Is it OK to take absolute value of NSTimeInterval?


Needed positive time interval taken from given NSDate. Both methods below do that.

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:dateStart];
timerLbl.text=[[NSDateComponentsFormatter new] stringFromTimeInterval:timeInterval];

OR

NSTimeInterval timeInterval = fabs([dateStart timeIntervalSinceNow]);
timerLbl.text=[[NSDateComponentsFormatter new] stringFromTimeInterval:timeInterval];

Was wondering if the last method was OK. Appreciate your input.


Solution

  • Of course it's ok.

    The property timeIntervalSinceNow is a computed property of a Date instance. It tells you how many seconds in the future a given date is.

    If you ask a date in the past how many seconds in the future it is, it will give you an answer that's a negative number.

    If instead you want to know how many seconds in the past a date is, use fabs()