IOS斯威夫特。自约会以来的时间

时间:2015-01-05 23:58:48

标签: ios swift nsdateformatter

我想要一个字符串给出的给定日期以来的月数和天数。

d是日期的字符串

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yy"
    let date = dateFormatter.dateFromString(d)
    startTime = date?.timeIntervalSinceReferenceDate

我理想地喜欢自该日期以来的月,日,分钟,但是一旦我通过此错误,我将会工作。编译器抱怨最后一行。

由于

1 个答案:

答案 0 :(得分:8)

您需要使用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.