How can I print a day of the week in a locale-friendly way using NSDateFormatter?

陌路散爱 提交于 2019-12-25 06:26:50

问题


I noticed NSDateFormatter allows for an enum called .FullStyle that will print Tuesday, April 12, 1952 AD.

But how do I just print Tuesday in a locale-safe way?


回答1:


You need to use NSDateFormatter dateFormat = "cccc". If you need a reference for date format patterns you can take a look at this link:

extension NSDate {
    struct Formatter {
        static let dayOfWeek: NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.dateFormat = "cccc"   // Stand Alone local day of week
            return formatter
        }()
    }
    var dayOfWeek: String {
        return Formatter.dayOfWeek.stringFromDate(self)
    }
}

print(NSDate().dayOfWeek)   // Wednesday

Xcode 8 beta 3 • Swift 3

extension DateFormatter {
    convenience init(dateFormat: String) {
        self.init()
        self.dateFormat = dateFormat
    }
}

extension Date {
    struct Formatter {
        static let dayOfWeek = DateFormatter(dateFormat: "cccc")  // Stand Alone local day of week
    }
    var dayOfWeek: String {
        return Formatter.dayOfWeek.string(from: self)
    }
}

print(Date().dayOfWeek)   // Wednesday



回答2:


You can set formatter.dateFormat = "EEEE" as Leo Dabus suggests.

If you have the day of week, you can use it as an index into the formatter's weekdaySymbols. Example:

let formatter = NSDateFormatter()
let weekday = formatter.calendar.component(.Weekday, fromDate: NSDate())
let weekdaySymbol = formatter.weekdaySymbols[weekday]
// result: "Saturday" (for example)


来源:https://stackoverflow.com/questions/36511423/how-can-i-print-a-day-of-the-week-in-a-locale-friendly-way-using-nsdateformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!