我正在尝试将字符串日期转换为日期类型。但是,当我在比较两个日期后尝试下面给出的代码时,返回 nil 值,一个是从日期选择器中选择的日期,第二个是当前日期,但始终给出我的返回编号。
我真的很困惑如何将字符串日期转换为日期类型,在比较两个日期后,请检查下面的代码:
代码
let currentDate = Date()
let currentDformatter = DateFormatter()
currentDformatter.dateFormat = "dd-MM-yyyy"
let currentDateResult = currentDformatter.date(from: "\(currentDate)")
print("Current Latest Date ",currentDateResult as Any)
let selectedDate = Date()
let selectedDformatter = DateFormatter()
selectedDformatter.dateFormat = "dd-MM-yyyy"
let selectedresult = selectedDformatter.string(from: selectedDate)
print("Current Latest Date ",selectedresult)
if currentDateResult == selectedDate{
print("yes")
}else{
print("no")
}
我也在比较时间,请给我建议,如何防止用户在时间选择器中选择超过特定时间的时间。例如餐厅关门时间是 5 点。
代码:
CurrentDateAndTime 2019-04-15 05:00:00 +0000
SelectDateAndTime 2019-04-16 07:52:28 +0000
我不希望用户选择5点之后的时间,我如何检查和比较时间?
如何查看和比较时间?
最佳答案
有更好的方法来检查两个日期是否在同一天
let currentDate = Date()
let selectedDate = Date()
if Calendar.current.isDate(currentDate, inSameDayAs: selectedDate) {
print("yes")
} else {
print("no")
}
关于ios - Swift 比较日期与字符串日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55683946/