我正在构建一个计算两个日期之间天数的应用。当我将结果打印到控制台时,我得到一些代码,我想从结果中删除它:
我尝试通过拆分字符串来删除不需要的代码,使用' componentsSeparatedByString'。
但是,为了使用这种方法,我必须首先转换'组件'常量为NSString。当我尝试这样做时,我收到一条错误消息:无法为类型' NSString'调用初始值设定项。使用类型'(字符串:NSDateComponents)'
的参数列表@IBAction func calculateDays(sender: AnyObject) {
let start = String(firstSelectedDate.text!)
let end = String(secondSelectedDate.text!)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let startDate:NSDate = dateFormatter.dateFromString(start)!
let endDate:NSDate = dateFormatter.dateFromString(end)!
let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = NSCalendarUnit.NSDayCalendarUnit
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: [])
let newComponents = NSString(string: components) // Cannot invoke initializer for type 'NSString' with an argument list of type '(string: NSDateComponents)'
let componentsArray = newComponents?.componentsSeparatedByString("<NSDateComponents: 0x7f91aaf29980>")
print(componentsArray[1])
如果有人能告诉我自己做错了什么,我将非常感激。
提前致谢!
答案 0 :(得分:1)
获得components
变量后,您可以检索day
属性,请尝试此操作:
let start = "2010-09-01"
let end = "2010-09-08"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter.dateFromString(start)!
let endDate:NSDate = dateFormatter.dateFromString(end)!
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
print(components.day) // 7
我希望这对你有所帮助。