0

NSLocale.autoupdatingCurrentLocale() makes formatting i18n dates really easy.

For example:

NSDate().descriptionWithLocale(NSLocale.autoupdatingCurrentLocale()

Returns:

Monday, February 1, 2016 at 12:00:00 PM Pacific Standard Time

Is there a way I can modify this simple function to return just the date? If not, how would I build out an equivalent NSLocale object that behaves the same way, deriving the an appropriate international date string?

I would expect, for en_US, it could return simply:

Monday, February 1, 2016
brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • just use NSDateFormatter `.dateStyle = .FullStyle`. The locale it is the current locale by default. If you would like a specific locale just set your dateFormatter.locale to whatever you need – Leo Dabus Jan 29 '16 at 19:36
  • `let df = NSDateFormatter() df.locale = NSLocale(localeIdentifier: "pt_BR") df.dateStyle = .FullStyle df.stringFromDate(NSDate()) ` – Leo Dabus Jan 29 '16 at 19:39
  • 1
    Ah, thanks Leo. Toss this in as an answer and I'll accept. `extension NSDate() { func asFullStyle() -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .FullStyle return dateFormatter.stringFromDate(self) } }` – brandonscript Jan 29 '16 at 19:40

1 Answers1

1

You can just use NSDateFormatter .dateStyle = .FullStyle. The locale it is the current locale by default. If you would like a specific locale just set your formatter.locale to whatever you need

extension NSDate {
    struct Date {
        static let localizedFormatter: NSDateFormatter = {
           let formatter = NSDateFormatter()
            formatter.dateStyle = .FullStyle
            return formatter
        }()
    }
    var localizedDecription: String {
        return Date.localizedFormatter.stringFromDate(self)
    }
}

NSDate().localizedDecription   // Friday, January 29, 2016"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571