LoginSignup
30
31

More than 5 years have passed since last update.

NSCalendarを使ったNSDateの日数の加算、2つの日時の差分、月日時などの取得

Last updated at Posted at 2015-11-06

いろいろ調べたところ、あまりまとまっているものがなかったので、NSCalendarを使ったNSDateの扱い方についてまとめてみました。

Xcode: 7.1
Swift: 2.1

//NSCalendarインスタンス
let cal = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
//* 海外の情報だとNSCalendar.currentCalendar()を使っているものが多いが、日本の場合、和暦に設定しているとバグる可能性があるので使わないほうがよいらしい。

//現在
let now = NSDate()

//10日後
let in10days = cal.dateByAddingUnit(.Day, value: 10, toDate: now, options: NSCalendarOptions())

//3ヶ月前
let before3Months = cal.dateByAddingUnit(.Month, value: -3, toDate: now, options: NSCalendarOptions())



//日時指定
//* eraValueとは紀元前:0, 紀元後:1
let date_2015_11_15_20_15 = cal.dateWithEra(1, year: 2015, month: 11, day: 15, hour: 20, minute: 15, second: 0, nanosecond: 0)!

//月を取得
let month = cal.component(.Month, fromDate: date_2015_11_15_20_15) // => 11

//時間を取得
let hour = cal.component(.Hour, fromDate: date_2015_11_15_20_15) // => 20



//2つの日時の差分
let unitFlags: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second]
let components = cal.components(unitFlags, fromDate: before3Months!, toDate: in10days!, options: NSCalendarOptions())

print(components.year) // 0
print(components.month) //3
print(components.day) //10
print(components.hour) //0
print(components.minute) //0
print(components.second) //0


//もしも2つの日時の差分を日数でほしいなら
let componentsByDay = cal.components([.Day], fromDate: before3Months!, toDate: in10days!, options: NSCalendarOptions())

print(componentsByDay.day) // 102
30
31
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
30
31