如何打印星期几的名称? [英] How to print name of the day of the week?

查看:109
本文介绍了如何打印星期几的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打印出星期几的名称,即星期一,星期二,星期三。我目前有这样的代码就是这样做的。我想知道是否有办法摆脱我的switch语句并使其更好。谢谢!

Im trying to print out the name of the day of the week i.e Monday, Tuesday, Wednesday. I currently have this bit of code that does just that. I was wondering if there is a way to get rid of my switch statement and make this better. Thanks!

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

打印出星期一

推荐答案

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

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

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

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
}

游乐场测试:

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

这篇关于如何打印星期几的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆