【问题标题】:Swift - Date String CompareSwift - 日期字符串比较
【发布时间】:2020-11-20 13:30:00
【问题描述】:

我正在尝试将字符串日期 (StringDate = "MMM dd, yyyy") 与今天的日期进行比较,但如果月份不同,则代码并不总是有效。有什么想法吗?

let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
dateFormatter.dateFormat = "MMM dd, yyyy"       
let dateWithTime = Date()
let dateFormatter2 = DateFormatter()
dateFormatter2.dateStyle = .medium
var currentDay = dateFormatter2.string(from: dateWithTime) 
if currentDay.count != 12 {
    currentDay.insert("0", at: currentDay.index(currentDay.startIndex, offsetBy: 4))
}       
if stringDate < currentDay {
    print("Date is past")
}

【问题讨论】:

    标签: swift date datetime compare dateformatter


    【解决方案1】:

    这是一个将给定字符串转换为日期并将其与给定 dat 进行比较的函数(默认为今天)。通过使用startOfDay(for:),比较中会忽略时间

    func before(_ string: String, date: Date = Date()) -> Bool? {
        let locale = Locale(identifier: "en_US_POSIX")
    
        let dateFormatter = DateFormatter()
        dateFormatter.locale = locale
        dateFormatter.dateFormat = "MMM dd, yyyy"
    
        guard let inDate = dateFormatter.date(from: string) else {
            return nil
        }
        var calendar = Calendar.current
        calendar.locale = locale
        return inDate < calendar.startOfDay(for: date)
    }
    

    【讨论】:

      【解决方案2】:

      问题在于日期是按字典顺序排列的。即使是数字,年份也应该在字符串中的月份之前,以便您能够比较日期字符串。 Swift 中的日期是可比较的,如果你想做一个时间不敏感的比较,你只需要使用中午时间。因此,您需要解析您的日期字符串,获取中午并将其与今天的中午进行比较。

      extension Date {
          static var noon: Date { Date().noon }
          var noon: Date { Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)! }
          var isInToday: Bool { Calendar.current.isDateInToday(self) }
          var isInThePast: Bool { noon < .noon }
          var isInTheFuture: Bool { noon > .noon }
      }
      

      游乐场测试:

      let dateFormatter = DateFormatter()
      dateFormatter.locale = Locale(identifier: "en_US_POSIX")
      dateFormatter.dateFormat = "MMM dd, yyyy"
      let stringDate = "Oct 20, 2020"
      if let date = dateFormatter.date(from: stringDate) {
          if date.isInThePast {
              print("Date is past")  // "Date is past\n"
          } else if date.isInToday {
              print("Date is today")
          } else {
              print("Date is future")
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多