import UIKit
func getDayOfWeek(_ date:String, format: String) -> String? {
let weekDays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]
let formatter = DateFormatter()
formatter.dateFormat = format
guard let myDate = formatter.date(from: date) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: myDate)
return weekDays[weekDay-1]
}
//testing date1
if let weekday = getDayOfWeek("04/24/2019", format:"MM/dd/yyyy") {
print(weekday)
} else {
print("Invalid Date")
}
//Result = Wednesday
//testing date2
if let weekday = getDayOfWeek("2019-04-23", format:"yyyy-MM-dd") {
print(weekday)
} else {
print("Invalid Date")
}
//Result = Tuesday
//testing date3
if let weekday = getDayOfWeek("2019-04-23", format:"MM/dd/yyyy") {
print(weekday)
} else {
print("Invalid Date")
}
//Result = Invalid Date
All one can think and do in a short time is to think what one already knows and to do as one has always done!