Basically, I'm getting a date time string from an API, and I want to show in the app that this activity happened '5 hours ago' or '3 days ago', and so on...
I am currently trying to get the NSTimeInterval from [NSDate timeIntervalSinceNow]
method. And then converting the time interval to NSDate again using [NSDate dateWithTimeIntervalSince1970:interval]
. And then checking the interval to see if its less that 60/3600/86400/etc, to set the right format for an output NSDateFormatter object.
Is this the right way to do it? Or is there a easier/better way to do this?
It's much better to use NSCalendar for this. It's designed for this sort of conversion.
NSUInteger desiredComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSDayCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *elapsedTimeUnits = [[NSCalendar currentCalendar] components:desiredComponents
fromDate:activityDate
toDate:[NSDate date]
options:0];
Check out this project: https://github.com/kevinlawler/NSDate-TimeAgo
It is a category for NSDate which does this.
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