LoginSignup
15
13

More than 5 years have passed since last update.

RSSで取得したpubDateをNSDateFormatterで変換(Swift)

Posted at

ロケールが日本語の時に上手く日付を取得できなかったので、残しておく。
Wed, 04 Nov 2015 15:02:11 +0000
上記のような書式の日付を
11月04日(水)
に変更します。

        // string = "Wed, 04 Nov 2015 15:02:11 +0000"
        let identifier = NSLocale.currentLocale().localeIdentifier

        if identifier == "ja_JP" {
            let dateFormatter = NSDateFormatter()
            // 書式が変わらない固定ロケールで一度値を取得
            dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
            dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss ZZZZ"
            let r_date = dateFormatter.dateFromString(string!)

            if let d = r_date {
                 // ロケールを日本語にして曜日を取得
                dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") 
                dateFormatter.dateFormat = "MM月dd日(E)"
                tmpEntry.addObject(dateFormatter.stringFromDate(d))
            }
        }
        // 日本語以外
        else{

        }

localeIdentifierを一度en_US_POSIXにするのがポイント。

参考

NSDateFormatterの使い方まとめ
http://qiita.com/gonsee/items/d3fb641914d2ca45e858

Swiftで現在日時を取得し、独自のフォーマットで出力する方法
http://qiita.com/cotrpepe/items/261833c465af5d70f867

15
13
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
15
13