Skip to content

Instantly share code, notes, and snippets.

@Mohsenqaysi
Last active September 20, 2018 16:13
Show Gist options
  • Save Mohsenqaysi/51b46873f5263b0bca38fbf7eb8c19de to your computer and use it in GitHub Desktop.
Save Mohsenqaysi/51b46873f5263b0bca38fbf7eb8c19de to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
let now = Date()
let pastDate = Date(timeIntervalSinceNow: -60 * 60 * 24 * 7 * 4 * 4)
//
//extension Date {
// func toShortDate(_ date: Date) -> String {
// let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "MMM dd"
// return dateFormatter.string(from: date)
// }
//}
//extension Date {
// func toFullDate(_ date: Date) -> String {
// let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "dd/MM /yyyy"
// return dateFormatter.string(from: date)
// }
//}
extension Date {
func timeAgoDisplay(_ date: Date) -> String {
let secondsAgo = Int(Date().timeIntervalSince(date))
let dateFormatter = DateFormatter()
let minute = 60
let hour = 60 * minute
let day = 24 * hour
let week = 7 * day
let month = 4 * week
let moreThanOneMonth = 5 * week
if secondsAgo < minute {
return "\(secondsAgo) seconds ago"
} else if secondsAgo < hour {
return "\(secondsAgo / minute) minutes ago"
} else if secondsAgo < day {
return "\(secondsAgo / hour) hours ago"
} else if secondsAgo < week {
return "\(secondsAgo / day) days ago"
} else if secondsAgo < month {
return "\(secondsAgo / week) weeks ago"
} else if secondsAgo < moreThanOneMonth {
dateFormatter.dateFormat = "MMM dd"
dateFormatter.string(from: date)
return "\(dateFormatter.string(from: date))"
}
dateFormatter.dateFormat = "dd/MM /yyyy"
return "\(dateFormatter.string(from: date))"
}
}
pastDate.timeAgoDisplay(pastDate)
// Full date formate like Facebook massnegr
// March 20 -> short date
// 20/03/2017 -> full date
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment