在Swift中比较日期字符串与今天的日期

zd287kbt  于 2023-04-04  发布在  Swift
关注(0)|答案(3)|浏览(136)

我正在尝试将字符串中的给定日期与今天的日期进行比较

func getDateFromDateString(date: String) -> Date {
      let dateFormatter = DateFormatter()
      dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
      dateFormatter.dateFormat =  "yyyy-MM-dd"//"yyyy-MM-dd'T'HH:mm:ssZ"
      let date = dateFormatter.date(from:date) ?? Date()
    return date
}

let ticketDate = getDateFromDateString(date: "2023-04-04")
        
let currentDate = Date()

if currentDate >  ticketDate {
  print("Expired")
} else {
  print("Active")
}

结果应该是活动的,但它已过期,我不知道为什么

h43kikqp

h43kikqp1#

更换管路

if currentDate > ticketDate {

if Calendar.current.compare(currentDate, 
                            to: ticketDate, 
                            toGranularity: .day) == .orderedAscending {

它比较忽略比day重要性低的日期组件的日期

crcmnpdw

crcmnpdw2#

替换代码如下

func getDateFromDateString(dateString: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    let date = dateFormatter.date(from: dateString)
    return date
}

func todayDate() -> Date{
    let currentDate = Date()
    let calendar = Calendar.current

    let year = calendar.component(.year, from: currentDate)
    let month = calendar.component(.month, from: currentDate)
    let day = calendar.component(.day, from: currentDate)

    var dateComponents = DateComponents()
    dateComponents.year = year
    dateComponents.month = month
    dateComponents.day = day

    let date = calendar.date(from: dateComponents)!
    return date
}

let currentDate = todayDate()

let ticketDate = getDateFromDateString(dateString: "2023-04-04")!

if ticketDate >= currentDate {
    print("Active")
} else {
    print("Expired")
}

在您的代码中,当前日期也有时间,所以请从今天的日期中删除时间。因此,它与时间进行比较,它会发现更大,并打印为过期。为了更好的解决方案,请使用完整的日期,即时间。如果您想知道更多,请发表评论。我很乐意解释。

ohfgkhjo

ohfgkhjo3#

func getDateFromDateString(date: String) -> Date {
      let dateFormatter = DateFormatter()
      dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
      dateFormatter.dateFormat =  "yyyy-MM-dd HH:mm:ss"//"yyyy-MM-dd'T'HH:mm:ssZ"
      let date = dateFormatter.date(from:date) ?? Date()
    return date
}

let ticketDate = getDateFromDateString(date: "2023-04-04 16:12:30")
        
let currentDate = Date()

if currentDate >  ticketDate {
  print("Expired")
} else {
  print("Active")
}

你检查当前日期,所以你需要检查与完整的日期一样给出的例子。

相关问题