SJP*_*SJP 6 nsdateformatter ios swift
我想要一个字符串给出的给定日期以来的月数和天数.
d是日期的字符串
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yy"
let date = dateFormatter.dateFromString(d)
startTime = date?.timeIntervalSinceReferenceDate
Run Code Online (Sandbox Code Playgroud)
理想情况下,我会喜欢自该日期以来的月,日,分钟,但是一旦我通过此错误,我将继续工作.编译器抱怨最后一行.
谢谢
您需要使用a 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.")
}
Run Code Online (Sandbox Code Playgroud)
输出(2014-01-05):
It's been 3 months and 21 days.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2049 次 |
| 最近记录: |