sar*_*rah 21 cocoa ios swift swift2
我把这一天的名字命名为
func loadDayName(forDate date: NSDate) -> String{
let myComponents = calendar.components(.Weekday, fromDate: date)
let weekDay = myComponents.weekday
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 "Nada"
}
}
Run Code Online (Sandbox Code Playgroud)
它是工作查找,但我想知道swift是否自带一些库自动比我在手动代码中做得更好
Leo*_*Leo 64
使用 DateFormatter
斯威夫特4
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let dayInWeek = dateFormatter.string(from: date)
Run Code Online (Sandbox Code Playgroud)
Swift3
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE" // "EE" to get short style
let dayInWeek = dateFormatter.stringFromDate(date) // "Sunday"
Run Code Online (Sandbox Code Playgroud)
截图
如果要获取日期名称数组,可以使用: weekdaySymbols in Calendar()
例:
let calendar = Calendar(identifier: .gregorian)
let days = calendar.weekdaySymbols
Run Code Online (Sandbox Code Playgroud)
自 iOS 15 以来有一个新的 api。
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
extension FormatStyle where Self == Date.FormatStyle {
public static var dateTime: Date.FormatStyle { get }
}
Run Code Online (Sandbox Code Playgroud)
您现在可以使用:
Date().formatted(.dateTime.month(.wide)) // October
Date().formatted(.dateTime.year(.defaultDigits)) // 2022
Date().formatted(.dateTime.weekday(.wide)) // Thursday
Date().formatted(.dateTime.weekday(.abbreviated)) // Thu
Date().formatted(.dateTime.weekday(.narrow)) // T
Run Code Online (Sandbox Code Playgroud)
等等等等
| 归档时间: |
|
| 查看次数: |
13083 次 |
| 最近记录: |