簡體   English   中英

比較兩個日期 - Swift

[英]Compare two date - Swift

如何在沒有time date format的情況下轉換string (如( 2019-11-02 )並在沒有time的情況下獲取當前Date設備,然后一起compare

除了上面使用日期的字符串表示之外,您實際上可以只使用日期本身。 只需轉換字符串即可為您提供“一天的開始”日期。 日歷有一個方法可以對日期執行相同的操作,允許您將轉換后的字符串與“今天”進行比較

func isDateToday(dateString: String) -> Bool {
  let df = DateFormatter()
  df.dateFormat = "yyyy-MM-dd"
  let date = df.date(from: dateString)
  let today = Calendar.current.startOfDay(for: Date())
  return date == today
}

您可以使用 dateFormatter 將字符串轉換為日期,然后使用 if 語句與當前日期進行比較

import Foundation

//convert string to date

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let myDate = dateFormatter.date(from: "2019-11-02")


//convert today's date in the same formate

let currentFormatter = DateFormatter()
currentFormatter.dateStyle = .short
currentFormatter.dateFormat = "yyyy-MM-dd"
let today = currentFormatter.string(from: Date())
let todayDate = dateFormatter.date(from: today)

//Compare the two date's

if myDate == todayDate {
    print("ok")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM