How to print name of the day of the week?

非 Y 不嫁゛ 提交于 2019-12-01 14:49:21

You are using the wrong date format. The correct format is "yyyy-M-d". Besides that you can use Calendar property weekdaySymbols which returns the weekday localized.

func getDayOfWeek(_ date: String) -> String? {
    let formatter  = DateFormatter()
    formatter.dateFormat = "yyyy-M-d"
    formatter.locale = Locale(identifier: "en_US_POSIX")
    guard let todayDate = formatter.date(from: date) else { return nil }
    let weekday = Calendar(identifier: .gregorian).component(.weekday, from: todayDate)
    return Calendar.current.weekdaySymbols[weekday-1] // "Monday"
}

Another option is to use DateFormatter and set your dateFormat to "cccc" as you can see in this answer:

extension Formatter {
    static let weekdayName: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "cccc"
        return formatter
    }()
    static let customDate: DateFormatter = {
        let formatter  = DateFormatter()
        formatter.dateFormat = "yyyy-M-d"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        return formatter
    }()
}
extension Date {
    var weekdayName: String {
        return Formatter.weekdayName.string(from: self)
    }
}

Using the extension above your function would look like this:

func getDayOfWeek(_ date: String) -> String? {
    return Formatter.customDate.date(from: date)?.weekdayName
}

Playground testing:

getDayOfWeek("2018-3-5")  // Monday
Date().weekdayName        // Thursday

Use this function:

func DayOfWeek(date: String) -> String?
{
    let dateFormatter  = DateFormatter()
    dateFormatter.dateFormat = "yyyy-M-d"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    guard let _date = dateFormatter.date(from: date) else { return nil }
    let weekday = Calendar(identifier: .gregorian).component(.weekday, from: _date)
    return Calendar.current.weekdaySymbols[weekday-1]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!