MeloS
MeloS

Reputation: 7938

Remove some part of formatted string from NSDateFormatterLongStyle

When working with date formatting in Chinese, for date Jan, 17, 2015, if in Chinese locale, with NSDateFormatterLongStyle, it will yield:

2015年1月17日

this is fine, but when I want only the month and year like this:

2015年1月

there is no such predefined format for this.

If using format template, the template will be @"YYYY年MM月", but this is not localizable for other locales like Japanese.

Is there any way to extract month and year from the long style format for all locales?

Upvotes: 1

Views: 184

Answers (1)

tia
tia

Reputation: 9698

Playground test:

let lc = "zh-cn";
var locale = NSLocale(localeIdentifier: lc);
var format = NSDateFormatter.dateFormatFromTemplate("yyyyMMM", 
    options: 0, locale: locale);
var formatter = NSDateFormatter();
formatter.dateFormat = format;
formatter.locale = locale;
formatter.stringFromDate(NSDate());

Production code:

var format = NSDateFormatter.dateFormatFromTemplate("yyyyMMM", 
    options: 0, locale: nil);
var formatter = NSDateFormatter();
formatter.dateFormat = format;
let dateString = formatter.stringFromDate(NSDate());

Upvotes: 1

Related Questions