我试图打印出星期几的名称,即星期一,星期二,星期三。我目前有这样的代码就可以做到这一点。我想知道是否有办法摆脱我的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")
打印出"星期一"
答案 0 :(得分:4)
您使用的日期格式错误。正确的格式为"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"
,如您在此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)
}
}
使用上面的扩展程序看起来像这样:
func getDayOfWeek(_ date: String) -> String? {
return Formatter.customDate.date(from: date)?.weekdayName
}
游乐场测试:
getDayOfWeek("2018-3-5") // Monday
Date().weekdayName // Thursday
答案 1 :(得分:0)
使用此功能:
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]
}