How to get time (hour, minute, second) in Swift 3 using NSDate?

SaRaVaNaN DM picture SaRaVaNaN DM · Jul 7, 2016 · Viewed 132.5k times · Source

How can you determine the hour, minute and second from NSDate class in Swift 3?

In Swift 2:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Hour, fromDate: date)
let hour = components.hour

Swift 3?

Answer

SaRaVaNaN DM picture SaRaVaNaN DM · Jul 7, 2016

In Swift 3.0 Apple removed 'NS' prefix and made everything simple. Below is the way to get hour, minute and second from 'Date' class (NSDate alternate)

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")

Like these you can get era, year, month, date etc. by passing corresponding.