我试图比较两个日期之间的天数 - (当前日期和用户选择日期) - 并将差异存储在变量var daysleft = 0
但是,我使用的代码daysleft
总是显示1天太少。基本术语:当前日期和明天日期结果具有相同的值(0
)
比较代码;
var daysleft = 0
let DayDifference = userCalendar.components(
dayCalendarUnit,
fromDate: Date,
toDate: dateView.date,
options: [])
daysleft = DayDifference.day
额外代码;
如果您需要查看用户选择的日期代码,可以使用以下代码;
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
DateTextField.text = dateFormatter.stringFromDate(sender.date)
dateMakerFormatter.calendar = userCalendar
dateMakerFormatter.dateFormat = "yyyy/MM/dd"
}
修改
以下是我使用的日期;
当前日期为;
let Date = NSDate()
用户选择的日期;
var datePickerView:UIDatePicker = UIDatePicker()
let dayCalendarUnit: NSCalendarUnit = [.Day]
let dateFormatter = NSDateFormatter()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
DateTextField.text = dateFormatter.stringFromDate(sender.date)
dateMakerFormatter.calendar = userCalendar
dateMakerFormatter.dateFormat = "yyyy/MM/dd"
}
比较;
dayCalendarUnit,
fromDate: Date,
toDate: datePickerView.date,
options: [])
daysleft = DayDifference.day
答案 0 :(得分:0)
问题是这两个日期之间没有一整天的差异(24 +小时)。
您需要获得每个component:fromDate:
的日期并减去天数。您可能需要处理数月和数年。
或
在使用components:fromDate:toDate:options:
计算日差之前,将时间设置为0。
答案 1 :(得分:0)
由于您的today
有时间,因此与用户的选择日期相差不到24小时。
您需要关闭时间组件:
let userCalendar = NSCalendar.currentCalendar()
// Only get the Year, Month, Day of `now`
let components = userCalendar.components([.Year, .Month, .Day], fromDate: NSDate())
let today = userCalendar.dateFromComponents(components)!
// Assume the user picked Mar 28, 2016
let userPickedDate = userCalendar.dateWithEra(1, year: 2016, month: 3, day: 28, hour: 0, minute: 0, second: 0, nanosecond: 0)!
let dayDifference = userCalendar.components([.Day], fromDate: today, toDate: userPickedDate, options: [])
print(today)
print(userPickedDate)
print(dayDifference.day)