繁体   English   中英

比较日期和字符串日期值Swift

[英]Compare Date to String Date Value Swift

我正在尝试将字符串日期转换为日期类型。 但是,当我在将两个日期彼此比较之后尝试下面给出的此代码返回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")
}
let currentDate = Date()
let currentDformatter = DateFormatter()
currentDformatter.dateFormat = "dd-MM-yyyy"
let currentDateResult = currentDformatter.date(from: "\(currentDate)")
print("Current Latest Date ",currentDateResult as Any)

在上面的代码中,您实际上并没有将Date对象转换为String类型。 将其插值到字符串只会打印出对象及其属性。 您必须将日期对象转换为String。

let myDateInString = "22-08-2018"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd-MM-yyyy"
let date = formatter.date(from: myDateInString) // Optional
let stringVal = formatter.string(from: date!)
debugPrint(stringVal)

如果要比较两个日期,可以使用:

switch date1.compare(date2) {
case .orderedSame: break // exact same
case .orderedAscending: break // date2 comes after date1 in calendar
case .orderedDescending: break // date2 comes before date1 in calendar
}

如果您只想检查两个日期是否同一天,请使用@vadian的答案

您正在获取currentDateResultnil因为您没有传递正确的date String因此您需要将date转换为string然后将string传递给该string如下所示:

let currentDateResult = currentDformatter.date(from: currentDformatter.string(from: currentDate))

否则,您可以执行与上述@vadian答案相同的操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM