一尘不染

如何打印星期几的名称?

swift

我正在尝试打印星期几的名称,即星期一,星期二,星期三。我目前有一些代码可以做到这一点。我想知道是否有办法摆脱我的switch语句并使它变得更好。谢谢!

 func getDayOfWeek(_ today: String) -> String? {
    let formatter  = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    guard let todayDate = formatter.date(from: today) else { return nil }
    let myCalendar = Calendar(identifier: .gregorian)
    let weekDay = myCalendar.component(.weekday, from: todayDate)

    switch weekDay {
    case 1:
        return "Sunday"
    case 2:
        return "Monday"
    case 3:
        return "Tuesday"
    case 4:
        return "Wednesday"
    case 5:
        return "Thursday"
    case 6:
        return "Friday"
    case 7:
        return "Saturday"
    default:
        return ""
    }
}



getDayOfWeek("2018-3-5")

打印“星期一”


阅读 310

收藏
2020-07-07

共1个答案

一尘不染

您使用了错误的日期格式。正确的格式是"yyyy-M-d"。除此之外,您可以使用Calendar属性weekdaySymbols返回本地化的工作日。

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"
}

另一个选择是使用DateFormatter并将dateFormat设置为"cccc",您可以在此答案中看到:

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 { Formatter.weekdayName.string(from: self) }
}

使用函数上方的扩展名看起来像这样:

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

游乐场测试:

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