基本上,您只需要将当前日期转换为与您从第三方网站获得的日期相同的格式(或相反),以便您可以轻松地比较它们:
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EE MMM"
let firstPartStringDate = dateFormatter.string(from: currentDate)
dateFormatter.dateFormat = "yy"
let lastPartStringDate = dateFormatter.string(from: currentDate)
let day = Calendar.current.component(.day, from: currentDate)
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
guard let ordinalDay = formatter.string(for: day) else {
return
}
let finalDateString = firstPartStringDate + " \(ordinalDay) " + lastPartStringDate
print(finalDateString)
对于今天的当前日期,您将获得与从第三方网站获得的完全相同的格式:
Sun Sep 17th 17
更新:以下是如何将String
您从第三方网站获得的转换为Date
,然后将其与当前日期进行比较。这首先解决了st,nd,rd和th在里面的问题String
。
// This is the string you get from the website
var webDateString = "Sat 9th Sep 17"
// First, remove the st, nd, rd or th if it exists :
if let stSubrange = webDateString.range(of:"st") {
webDateString.removeSubrange(stSubrange)
} else if let ndSubrange = webDateString.range(of:"nd") {
webDateString.removeSubrange(ndSubrange)
} else if let rdSubrange = webDateString.range(of:"rd") {
webDateString.removeSubrange(rdSubrange)
} else if let thSubrange = webDateString.range(of:"th") {
webDateString.removeSubrange(thSubrange)
}
// Now convert the string to a date :
dateFormatter.dateFormat = "EE MMM dd yy"
guard let formattedDate = dateFormatter.date(from: finalDateString) else {
return
}
// You can now compare formattedDate and the current date easily like so :
let currentDate = Date()
if formattedDate < currentDate {
// Do something interesting here :)
} else {
// Do something else!
}