IOSSwift。自日期以来的时间
IOS Swift. Time since date
我想要从字符串给出的给定日期以来的月数和天数。
d 是一个日期字符串
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yy"
let date = dateFormatter.dateFromString(d)
startTime = date?.timeIntervalSinceReferenceDate
理想情况下,我希望自日期以来的月、日、分钟,但一旦我通过此错误,我将处理该部分。编译器抱怨最后一行。
谢谢
您需要使用 NSCalendar
来计算月数和天数的差异。示例:
let calendar = NSCalendar.autoupdatingCurrentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = calendar.timeZone
dateFormatter.dateFormat = "yyyy-MM-dd"
if let startDate = dateFormatter.dateFromString("2014-9-15") {
let components = calendar.components([ .Month, .Day ],
fromDate: startDate, toDate: NSDate(), options: [])
let months = components.month
let days = components.day
print("It's been \(months) months and \(days) days.")
}
输出(2014-01-05):
It's been 3 months and 21 days.
我想要从字符串给出的给定日期以来的月数和天数。
d 是一个日期字符串
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yy"
let date = dateFormatter.dateFromString(d)
startTime = date?.timeIntervalSinceReferenceDate
理想情况下,我希望自日期以来的月、日、分钟,但一旦我通过此错误,我将处理该部分。编译器抱怨最后一行。
谢谢
您需要使用 NSCalendar
来计算月数和天数的差异。示例:
let calendar = NSCalendar.autoupdatingCurrentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = calendar.timeZone
dateFormatter.dateFormat = "yyyy-MM-dd"
if let startDate = dateFormatter.dateFromString("2014-9-15") {
let components = calendar.components([ .Month, .Day ],
fromDate: startDate, toDate: NSDate(), options: [])
let months = components.month
let days = components.day
print("It's been \(months) months and \(days) days.")
}
输出(2014-01-05):
It's been 3 months and 21 days.