LoginSignup
9
7

More than 5 years have passed since last update.

Swiftで日付の形式を変換する

Posted at

RSSなどのデータで見かける以下の形式の日付データ

Sat, 02 May 2015 12:04:27 +0900

上記のこの形式の日付文字列を

2015/05/02 12:04

上記の形式に直します

func convertDateFormat(dateStr:String) -> String {
    // 引数で渡ってきた文字列をNSDateFormatterでNSDateに直します
    let inFormatter = NSDateFormatter()
    inFormatter.dateFormat = "EEE, dd MM yyyy HH:mm:ss Z"
    let date:NSDate = inFormatter.dateFromString(dateStr)!

    // NSDateから指定のフォーマットの文字列に変換します
    let outFormatter = NSDateFormatter()
    outFormatter.dateFormat = "yyyy/MM/dd HH:mm"

    return outFormatter.stringFromDate(date)
}

NSDateFormatterに渡す形式

  • yyyy : 年
  • MMM 月
  • dd : 日
  • EEE 曜日
  • HH : 時
  • mm : 分
  • ss : 秒
  • Z : 時差
9
7
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
7