[英]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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.