【发布时间】:2017-03-17 13:05:48
【问题描述】:
我在使用 NSDateFormatter 时遇到问题。我实现了一个日期选择器,您可以在其中选择两个日期来计算这两个日期之间的差异并以天为单位返回差异。这两个日期的格式如下(.MediumStyle):
var firstDate = "Nov 3, 2016"
var lastDate = "Nov 9, 2016"
但是,当它到达函数中名为calculateDifference() 的部分,其中这两个值被转换为NSDate 的类型时,该方法返回nil。
我的代码如下:
@IBOutlet weak var startDateOutput: UILabel! // shows start date user picked
@IBOutlet weak var endDateOutput: UILabel! // shows end date user picked
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var answerFieldTimeDifference: UILabel! // Output Field
var firstDate = ""
var lastDate = ""
@IBAction func startButton(sender: AnyObject) // Button to set firstDate
{
firstDate = NSDateFormatter.localizedStringFromDate(datePicker.date, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.NoStyle)
startDateOutput.text = firstDate
calculateDifference()
}
@IBAction func expirationButton(sender: AnyObject) // Button to set lastDate
{
lastDate = NSDateFormatter.localizedStringFromDate(datePicker.date, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.NoStyle)
endDateOutput.text = lastDate
calculateDifference()
}
func calculateDifference()
{
if !firstDate.isEmpty && !lastDate.isEmpty
{
let dateFormatter = NSDateFormatter()
let firstDateAsNSDate = dateFormatter.dateFromString(firstDate) //returns nil
let lastDateAsNSDate = dateFormatter.dateFromString(lastDate) //returns nil
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [NSCalendarUnit.Day]
var calculatedDifference = dateComponentsFormatter.stringFromDate(firstDateAsNSDate!, toDate: lastDateAsNSDate!)
answerFieldTimeDifference.text = calculatedDifference
}
}
【问题讨论】:
-
使用字符串完全没有意义。只需保留对两个
NSDate对象的引用即可。
标签: swift swift2 nsdate xcode7 nsdateformatter