【问题标题】:better way to get the name of the day on ios swift在 ios swift 上获取当天名称的更好方法
【发布时间】:2015-11-15 12:23:40
【问题描述】:

我这样取今天的名字

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

它正在工作,但我想知道 swift 是否带有一些库来自动执行此操作,而不是我在手动代码中执行此操作

【问题讨论】:

标签: ios swift cocoa swift2


【解决方案1】:

使用DateFormatter

斯威夫特 4

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let dayInWeek = dateFormatter.string(from: date)

Swift3

let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat  = "EEEE" // "EE" to get short style
let dayInWeek = dateFormatter.stringFromDate(date) // "Sunday"    

截图

【讨论】:

  • 这是一个不错的选择,但数组包含 ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] 而不是我想要的日子的全名
  • 有了shortWeekdaySymbols ,你可以得到短字符串。就像我更新的代码一样
  • 你怎么知道 weekdaysSymbols 包含全名?我打印了它,它们都包含短名称。 +1 的努力
  • weekdaysSymbols 在我的操场上运行良好。也可以使用dateFormatter。就像我更新的代码一样
  • 在 Swift 4 中,stringFromDate 现在是 formatter.string(from: now)
【解决方案2】:

如果您想获取可以使用的日期名称数组:weekdaySymbols in Calendar()

示例:

let calendar = Calendar(identifier: .gregorian)
let days = calendar.weekdaySymbols

【讨论】:

  • 是的,但是在您设置 calendar.locale 之后。
【解决方案3】:

你也可以检查这个 DateFormatter

let dayNameFormatter: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = .current
    dateFormatter.calendar = .current
    dateFormatter.dateFormat = "cccc"
    return dateFormatter
}()
print(dayNameFormatter.string(from: Date())) Prints today's day name ?

c - 代表星期几,good answerofficial source

【讨论】:

    猜你喜欢
    • 2011-08-02
    • 2016-03-13
    • 2011-01-04
    • 1970-01-01
    • 2012-11-16
    • 2010-09-19
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多