[英]Compare two date - Swift
How can I convert string
like ( 2019-11-02
) without time
to date format
and get current Date
device without time
then compare
with together?如何在没有
time
date format
的情况下转换string
(如( 2019-11-02
)并在没有time
的情况下获取当前Date
设备,然后一起compare
?
As well as the above using string representations of date, you can actually work with just the dates themselves.除了上面使用日期的字符串表示之外,您实际上可以只使用日期本身。 Just converting a the string will give you a "start of day" date.
只需转换字符串即可为您提供“一天的开始”日期。 The Calendar has a method which will do the same with a date, allowing you to compare the converted string to 'today'
日历有一个方法可以对日期执行相同的操作,允许您将转换后的字符串与“今天”进行比较
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
}
You can convert the string to date using a dateFormatter then compare with the current date using an if statement您可以使用 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.