问题
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