I want to check today's date with some other date which is in String
, if both are equals then need to perform some tasks.
I tried date1 < date2
but it is comparing date, I want equal check
I want to check today's date with some other date which is in String
, if both are equals then need to perform some tasks.
I tried date1 < date2
but it is comparing date, I want equal check
Dates are complicated... let Apple do it for you... Calendar date comparison
let date1 = // some date
let date2 = // some date
let isSameDay = Calendar.current.isDate(date1, equalTo: date2, toGranularity: .day)
let isSameHour = Calendar.current.isDate(date1, equalTo: date2, toGranularity: .hour)
let isSameMonth = Calendar.current.isDate(date1, equalTo: date2, toGranularity: .month)
etc...
This will work no matter which time zone, which calendar type is being used, etc...
compare both date string like,
if date1.stringWithFormatter(dateFormat: "yyyy-MM-dd") == Date().stringWithFormatter(dateFormat: "yyyy-MM-dd") {
// today's date
}else{
// not today's date
}
extension Date {
func stringWithFormatter(dateFormat: String) -> String {
let formatter: DateFormatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = dateFormat
return formatter.string(from: self)
}
func datefromString(string:String,dateFormat: String) -> Date {
let formatter: DateFormatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = dateFormat
return formatter.date(from: string)!
}
}
Use below code to check equal dates
func getCurrentDate() -> String {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let result = formatter.string(from: date)
print(result)
return result
}
Now check with your date
if self.getCurrentDate() == "01.01.2001" {
\\Your stuff to be added
print("Date found!!!")
}