Nico
Nico

Reputation: 6359

How to display only the day and month of a date based on the locale?

I would like to display only the day and the month of a date, but I want it based on the user's locale.

For example I have the following date: 21/05/2015 00:16:00 GMT+10

I want to have May 21 if the locale is en_US or 21 May if the locale if fr_FRfor example.

I looked with the dateStyle of NSDateFormatter formatter but couldn't find what I want.

Upvotes: 5

Views: 1243

Answers (2)

Roman Barzyczak
Roman Barzyczak

Reputation: 3813

You can use simple extension for it:

public extension NSDate {
func getNiceDate() -> String! {
    let dateFormatter = NSDateFormatter()
    let format = NSDateFormatter.dateFormatFromTemplate(
        "dMMMM", options:0, locale:NSLocale(localeIdentifier: "en_US"))
    dateFormatter.dateFormat = format

    return dateFormatter.stringFromDate(self)
}

}

Upvotes: 1

matt
matt

Reputation: 534977

Something along these lines, perhaps:

let d = // the date
let df = NSDateFormatter()
let format = NSDateFormatter.dateFormatFromTemplate(
    "dMMMM", options:0, locale:NSLocale.currentLocale())
df.dateFormat = format
let s = df.stringFromDate(d)

Note that both language and region settings on the device are involved in the outcome.

Upvotes: 7

Related Questions