30
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift]NSDateComponentで日付の各要素を取得

Last updated at Posted at 2014-07-28

年、月、日等の日付に関する各要素を一つ一つで取り出したいときはNSDateComponentを使います。

##コード

let date = NSDate()
let calendar = NSCalendar(identifier: NSGregorianCalendar)
//和暦を使いたいときはidentifierにはNSJapaneseCalendarを指定
//let calendar = NSCalendar(identifier: NSJapaneseCalendar)

var comps:NSDateComponents = calendar.components(NSCalendarUnit.YearCalendarUnit|NSCalendarUnit.MonthCalendarUnit|NSCalendarUnit.DayCalendarUnit|NSCalendarUnit.HourCalendarUnit|NSCalendarUnit.MinuteCalendarUnit|NSCalendarUnit.SecondCalendarUnit,
    fromDate: date)

var year = comps.year
var month = comps.month
var day = comps.day
var hour = comps.hour
var minute = comps.minute
var second = comps.second

println("\(year)/\(month)/\(day)/\(hour)/\(minute)/\(second)")
println("\(year)")
println("\(month)")
println("\(day)")
println("\(hour)")
println("\(minute)")
println("\(second)")

##出力結果
2014/7/28/17/23/59
2014
7
28
17
23
59

##まとめ
Objective-Cの頃は
NSCalendarUnit.YearCalendarUnit

NSYearCalendarUnit
と書いていました。
この書き方の違いがあり、最初にcalendar.componentsを指定する時に少し詰まりました。

時間関係の他に、
・曜日
・一年の何週目か
・第何四半期か
・今月の何週目か
などの要素も取り出せます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?