28
26

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で2つの年月日秒の差分を取りたい

Posted at

簡単にできるかと思ったけど意外と時間かかったし忘れそうなのでメモ

let start = "2000/10/09 23:58:59"
let end = "2041/10/09 00:00:00"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"

let startDate:NSDate? = dateFormatter.dateFromString(start)
let endDate:NSDate? = dateFormatter.dateFromString(end)

let cal = NSCalendar.currentCalendar()
let calUnit:NSCalendarUnit = .CalendarUnitSecond | .CalendarUnitMinute | .CalendarUnitHour | .CalendarUnitDay | .CalendarUnitYear

let components = cal.components(calUnit, fromDate: startDate!, toDate: endDate!, options: nil)

println(components.year)   //40
println(components.day)    //364
println(components.hour)   //0
println(components.minute) //1
println(components.second) //1

ブログに書いてみたけどやっぱりブログが続けられないのでこっちで書き溜めたい。

28
26
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
28
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?