Skip to content

Instantly share code, notes, and snippets.

@FarshidRoohi
Last active May 1, 2018 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FarshidRoohi/dd09436e751ccc0aceee3b950e5f6aab to your computer and use it in GitHub Desktop.
Save FarshidRoohi/dd09436e751ccc0aceee3b950e5f6aab to your computer and use it in GitHub Desktop.
show persian times ago e.x input method String date format : "yyyy-MM-dd HH:mm:ss"
import Foundation
class PrettyTime {
// example uses : PrettyTime.timesAgo(strDate : "2018-03-10 13:19:13" , numericDates : false)
static func timesAgo(strDate:String, numericDates:Bool) -> String {
var stringDate = strDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_ POSIX") as Locale?
if stringDate.isEmpty {
let date = Date()
stringDate = dateFormatter.string(from: date)
}
let date = dateFormatter.date(from: stringDate)
if date == nil {
return "invalid date string"
}
let calendar = NSCalendar.current
let now = NSDate()
let earliest = now.earlierDate(date!)
let latest = (earliest == now as Date) ? date : now as Date
let components = calendar.dateComponents([.minute, .hour, .day, .weekOfYear, .month, .year, .second], from: date! , to: latest!)
if (components.year! >= 2) {
return "\(String(describing: components.year!)) سال قبل"
} else if (components.year! >= 1){
if (numericDates){
return "۱ سال قبل"
} else {
return "سال قبل"
}
} else if (components.month! >= 2) {
return "\(String(describing: components.month!)) ماه پیش"
} else if (components.month! >= 1){
if (numericDates){
return "۱ ماه پیش"
} else {
return "یک ماه قبل"
}
} else if (components.weekOfYear! >= 2) {
return "\(String(describing: components.weekOfYear!)) هفته پیش"
} else if (components.weekOfYear! >= 1){
if (numericDates){
return "۱ هفته پیش"
} else {
return "یک هفته پیش"
}
} else if (components.day! >= 2) {
return "\(String(describing: components.day!)) روز قبل"
} else if (components.day! >= 1){
if (numericDates){
return "۱ روز قبل"
} else {
return "دیروز"
}
} else if (components.hour! >= 2) {
return "\(String(describing: components.hour!)) ساعت قبل"
} else if (components.hour! >= 1){
if (numericDates){
return "۱ ساعت قبل"
} else {
return "یک ساعت پیش"
}
} else if (components.minute! >= 2) {
return "\(String(describing: components.minute!)) دقیقه پیش"
} else if (components.minute! >= 1){
if (numericDates){
return "۱ دقیقه پیش"
} else {
return "یک دقیقه پیش"
}
} else if (components.second! >= 3) {
return "\(String(describing: components.second!)) ثانیه پیش"
} else {
return "چند لحظه پیش"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment