eliu2016 / Swap

Repository for iOS Application - Swap
2 stars 1 forks source link

Date #41

Closed MichealSBingham closed 7 years ago

MichealSBingham commented 7 years ago

Put this code in the utility file

Here is an example how to use it

     let dateNumber = user._date // something like that I think
    dateNumber.timeAgo() //prints the string 

extension NSNumber{

func timeAgo() -> String {

    let date = Date(timeIntervalSince1970: TimeInterval(self))

    return timeAgoSinceDate(date: date as NSDate, numericDates: false)
}

}

extension Date{

   func timeAgo() -> String {

       return timeAgoSinceDate(date: self as NSDate, numericDates: false)
    }
 }

func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String {
let calendar = NSCalendar.current
let unitFlags: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfYear, .month, .year, .second]
let now = NSDate()
let earliest = now.earlierDate(date as Date)
let latest = (earliest == now as Date) ? date : now
let components = calendar.dateComponents(unitFlags, from: earliest as Date,  to: latest as Date)

if (components.year! >= 2) {
    return "\(components.year!) years ago"
  } else if (components.year! >= 1){
      if (numericDates){
          return "1 year ago"
        } else {
           return "Last year"
        }
      } else if (components.month! >= 2) {
     return "\(components.month!) months ago"
    } else if (components.month! >= 1){
        if (numericDates){
             return "1 month ago"
         } else {
           return "Last month"
     }
      } else if (components.weekOfYear! >= 2) {
         return "\(components.weekOfYear!) weeks ago"
     } else if (components.weekOfYear! >= 1){
         if (numericDates){
         return "1 week ago"
       } else {
        return "Last week"
            }
       } else if (components.day! >= 2) {
     return "\(components.day!) days ago"
     } else if (components.day! >= 1){
     if (numericDates){
            return "1 day ago"
        } else {
        return "Yesterday"
         }
    } else if (components.hour! >= 2) {
        return "\(components.hour!) hours ago"
        } else if (components.hour! >= 1){
    if (numericDates){
        return "1 hour ago"
     } else {
        return "An hour ago"
    }
      } else if (components.minute! >= 2) {
    return "\(components.minute!) minutes ago"
     } else if (components.minute! >= 1){
    if (numericDates){
          return "1 minute ago"
          } else {
        return "A minute ago"
          }
     } else if (components.second! >= 3) {
    return "\(components.second!) seconds ago"
    } else {
        return "Just now"
      }

  }