【swift】日付時間処理

概要

swiftで日付時刻の処理を行う場合には、NSDate、NSCalendarクラスを使います。

NSDate, NSDateFormatterを使う方法

書式を使って時間を取得します

日付時刻の書式については、 ここを参照してください。

  // 現在時間を取得
  let now = NSDate()
  let formatter = NSDateFormatter()
  // yyyyMMdd HH:mm:ss
  formatter.dateFormat = "HH"

  // 時間を整数値に変換
  let hour = Int(formatter.stringFromDate(now))
  // 時間に応じて挨拶を変える
  if hour < 12 {
      print("Good Morning!")
  } else  if hour < 18 {
      print("Good Afternoon!")
  } else {
      print("Good Evening!")
  }

日付時刻の文字列フォーマットします

NSDateFormatterにlocaleを設定する、国別のの日付表示を取得できます。

// 2016/3/27の場合
let date = NSDate()
// US English Locale (en_US)
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
print(dateFormatter.stringFromDate(date)) // My 27, 2016

// French Locale (fr_FR)
dateFormatter.locale = NSLocale(localeIdentifier: "fr_FR")
print(dateFormatter.stringFromDate(date)) // 27 mars 2016

// Japanese Locale (ja_JP)
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP")
print(dateFormatter.stringFromDate(date)) // 2016/03/27

文字列表現をパーズしてNSDateに変換します

let RFC3339DateFormatter = NSDateFormatter()
RFC3339DateFormatter.locale = NSLocale(localeIdentifier: "ja_JP")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let string = "2016-03-27T16:39:57-08:00"
let date2 = RFC3339DateFormatter.dateFromString(string)
print(date2) // Optional(2016-03-28 00:39:57 +0000)

NSCalendarを使う方法

NSCalendarを使うと、年、月、日、時間、分、秒を個別に取得することができます。

  let now = NSDate()
  let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierJapanese)!
  let hour: NSDateComponents = calendar.components(NSCalendarUnit.Hour, fromDate: now)
  print(hour.hour)

日付計算もできます。が、ちょっと使うのは面倒。

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let date = calendar.dateByAddingUnit(.Day, value: 1, toDate: now, options: NSCalendarOptions())

参考情報