nipponese nipponese - 4 months ago 19
Swift Question

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

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?

Answer

You need to use NSDateFormatter dateFormat = "EEEE". 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