Posted By

dipenpatel on 02/06/16


Tagged

iphone NSDate ios


Versions (?)

Display date as Today, Tomorrow, 2 Days ago etc


 / Published in: Objective C
 

URL: http://apptraitsolutions.com

This snippet is used to covert any date to days like today, tomorrow, 2 days ago, 2 weeks ago or even 1 years ago.

  1. - (NSString *)relativeDateStringForDate:(NSDate *)date
  2. {
  3. NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear |
  4. NSCalendarUnitMonth | NSCalendarUnitYear;
  5.  
  6. // if `date` is before "now" (i.e. in the past) then the components will be positive
  7. NSDateComponents *components = [[NSCalendar currentCalendar] components:units
  8. fromDate:date
  9. toDate:[NSDate date]
  10. options:0];
  11.  
  12. if (components.year > 0) {
  13. return [NSString stringWithFormat:@"%ld years ago", (long)components.year];
  14. } else if (components.month > 0) {
  15. return [NSString stringWithFormat:@"%ld months ago", (long)components.month];
  16. } else if (components.weekOfYear > 0) {
  17. return [NSString stringWithFormat:@"%ld weeks ago", (long)components.weekOfYear];
  18. } else if (components.day > 0) {
  19. if (components.day > 1) {
  20. return [NSString stringWithFormat:@"%ld days ago", (long)components.day];
  21. } else {
  22. return @"Yesterday";
  23. }
  24. } else {
  25. return @"Today";
  26. }
  27. }

Report this snippet  

You need to login to post a comment.