我试图获得类似于facebook发布日期/时间的内容。比如1分钟,1小时,昨天,周等等。
这是我用来获取此格式的函数:(Oct-22 17:28 PM
)
func convertTime(serverTime: Double) -> String {
let serverTime = serverTime
let date = Date(timeIntervalSince1970: serverTime)
let dateFomatter = DateFormatter()
dateFomatter.dateFormat = "MMM-dd HH:mm a"
let strDate = dateFomatter.string(from: date)
print("This is the post's date: \(strDate)")
return strDate
}
答案 0 :(得分:3)
试试这段代码
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let before = dateFormatter.date(from: "2017-10-23 10:28:17")!
//getting the current time
let now = Date()
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1
formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute]
formatter.includesApproximationPhrase = true
let formatString = NSLocalizedString("%@ ago", comment: "e.g. '2 hours ago'")
let timeString = formatter.string(from: before, to: now)