我在String中创建了created_at(以2015-12-16 19:28:16
的形式)。我想将其与当前时间进行比较,并以5h
,35m
,3d
等形式给出时差...
我在SO answer找到了我可以使用扩展来实现这一点。这是扩展名:
extension NSDate {
func yearsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Year, fromDate: date, toDate: self, options: []).year
}
func monthsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Month, fromDate: date, toDate: self, options: []).month
}
func weeksFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.WeekOfYear, fromDate: date, toDate: self, options: []).weekOfYear
}
func daysFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Day, fromDate: date, toDate: self, options: []).day
}
func hoursFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Hour, fromDate: date, toDate: self, options: []).hour
}
func minutesFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Minute, fromDate: date, toDate: self, options: []).minute
}
func secondsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Second, fromDate: date, toDate: self, options: []).second
}
func offsetFrom(date:NSDate) -> String {
if yearsFrom(date) > 0 { return "\(yearsFrom(date))y" }
if monthsFrom(date) > 0 { return "\(monthsFrom(date))M" }
if weeksFrom(date) > 0 { return "\(weeksFrom(date))w" }
if daysFrom(date) > 0 { return "\(daysFrom(date))d" }
if hoursFrom(date) > 0 { return "\(hoursFrom(date))h" }
if minutesFrom(date) > 0 { return "\(minutesFrom(date))m" }
if secondsFrom(date) > 0 { return "\(secondsFrom(date))s" }
return ""
}
}
所以我可以使用dateWithEra()
并致电offsetFrom()
:
let date4 = NSCalendar.currentCalendar().dateWithEra(1, year: 2015, month: 11, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let timeOffset3 = NSDate().offsetFrom(date3) // "54m"
但是,我想在String中给它一个日期。
let myDate = post!["created_at"].string! // 2015-12-16 19:28:16
如何为其提供字符串以便能够转换3h
,30m
?我想我可以利用字符串并将其放在dateWithEra中,但有没有办法直接给它一个字符串?
还是我完全没法了?我想要实现的是获取字符串中的日期(2015-12-16 19:28:16格式)与当前时间之间的时差,并将其显示为"5h"
或"50m"
。< / p>
答案 0 :(得分:1)
要从格式化字符串中获取NSDate
,请使用NSDateFormatter
let dateString = "2015-12-16 19:28:16"
let inputFormatter = NSDateFormatter()
inputFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
let date = inputFormatter.dateFromString(dateString)!
如果您可以使用min
代替m
获取某些本地化中的分钟缩写,最简单的方法是NSDateComponentsFormatter
let outputformatter = NSDateComponentsFormatter()
outputformatter.allowedUnits = [.Day, .Hour, .Minute, .Second]
outputformatter.unitsStyle = .Abbreviated
let timeOffset = outputformatter.stringFromDate(date, toDate: NSDate())!
修改:
要始终m
而不是min
,请timeOffset
变为可变并添加
var timeOffset = outputformatter.stringFromDate(date, toDate: NSDate())!
if let minRange = timeOffset.rangeOfString("in") {
timeOffset = timeOffset.substringToIndex(minRange.startIndex) + timeOffset.substringFromIndex(minRange.endIndex)
}