LoginSignup
9
9

More than 5 years have passed since last update.

[swift]Web APIで取得した日付をNSDateに変換するextension

Posted at

2014-09-04T09:54:49+00:00の形式の文字列をNSDate型に変換、表示するときは読みやすい文字列に変換するためのextension

DateExtension.swift
import Foundation

extension NSDate {
    class func parse(dateString:String) -> NSDate {
        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssxxx"
        formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        let d = formatter.dateFromString(dateString)
        return NSDate(timeInterval: 0, sinceDate: d!)
    }

    func toString() -> String {
        let formatter = NSDateFormatter()
        formatter.dateStyle = NSDateFormatterStyle.MediumStyle
        formatter.timeStyle = NSDateFormatterStyle.ShortStyle
        return formatter.stringFromDate(self)
    }
}

最近のWebAPIだと2014-09-04T09:54:49+00:00のフォーマットで対応出来ると思うが、別のフォーマットの場合でもここを参考に変換できるはず。
http://userguide.icu-project.org/formatparse/datetime

9
9
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
9
9