There are already a lot of answers here but I think there's another, perhaps better, way of doing this using the correct Calendar
APIs.
I'd suggest getting the day of the week using the weekdaySymbols
property of Calendar
(docs) in an extension to Date
:
extension Date {
/// Returns the day of the week as a `String`, e.g. "Monday"
var dayOfWeek: String {
let calendar = Calendar.autoupdatingCurrent
return calendar.weekdaySymbols[calendar.component(.weekday, from: self) - 1]
}
}
This requires initialising a Date
first, which I would do using a custom DateFormatter
:
extension DateFormatter {
/// returns a `DateFormatter` with the format "yyyy-MM-dd".
static var standardDate: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}
}
This can then be called with:
DateFormatter.standardDate.date(from: "2018-09-18")!.dayOfWeek
Why I prefer this:
dayOfWeek
does not have to care about time zones because the
user's calendar is used, some of the other solutions here will show
the incorrect day because time zones are not considered. DateFormatter
and use that instead? weekdaySymbols
is localised for you.weekDaySymbols
can be replaced with other options such as shortWeekdaySymbols
for "Mon", "Tues" etc. Please note: This example DateFormatter
also doesn't consider time zones or locales, you'll need to set them for what you need. If the dates are always precise, consider setting the time zone TimeZone(secondsFromGMT: 0)
.