4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

現在のロケールに合わせて適切な日時の表記を得る

Last updated at Posted at 2016-01-12

簡単にやるには NSDateFormatterdateStyle に指定するのが一番早い。
しかし年は不要、短い表記で曜日が欲しい等、もう少しカスタマイズして表示したい場合は dateFormatFromTemplate:options:locale を使用すれば、ロケールと必要なフォーマット文字列を元に適切なフォーマット文字列を返してくれる。

func printDate( locale: NSLocale){
    if let formatString = NSDateFormatter.dateFormatFromTemplate(
        "MMMddE", 
        options: 0,
        locale: locale    ){
            let dateFormatter = NSDateFormatter()

            dateFormatter.dateFormat = formatString
            dateFormatter.locale = locale
            let formattedDateString = dateFormatter.stringFromDate(NSDate())
            print(formattedDateString)
    }
}
// 日本
let jpLocale = NSLocale.init(localeIdentifier: "ja_JP")
printDate(jpLocale) // -> "1月13日(水)"
// US
let usLocale = NSLocale.init(localeIdentifier: "en_US")
printDate(usLocale) // -> "Wed, Jan 13"
// イギリス
let gbLocale = NSLocale.init(localeIdentifier: "en_GB")
printDate(gbLocale) // -> "Wed 13 Jan"
// カレントのロケール
let currentLocale = NSLocale.currentLocale()
printDate(currentLocale) // -> "Wed, Jan 13"
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?