如何使用NSDate在Swift 3中获得时间(小时,分钟,秒)?

你如何确定Swift 3中NSDate类的小时,分​​钟和秒?

在Swift 2中:

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

Swift 3?

Swift 3.0中,苹果删除了“NS”前缀,并且使所有的事情变得简单。 以下是从“date”类(NSDate备用)获取小时,分钟和秒的方法

 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)") 

像这些你可以通过相应的时间,年份,月份,date等。

Swift 3.0

 // *** Create date *** let date = NSDate() // *** create calendar object *** var calendar = NSCalendar.current // *** Get components using current Local & Timezone *** print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date)) // *** define calendar components to use as well Timezone to UTC *** let unitFlags = Set<Calendar.Component>([.hour, .year, .minute]) calendar.timeZone = TimeZone(identifier: "UTC")! // *** Get All components from date *** let components = calendar.dateComponents(unitFlags, from: date as Date) print("All Components : \(components)") // *** Get Individual components from date *** let hour = calendar.component(.hour, from: date as Date) let minutes = calendar.component(.minute, from: date as Date) let seconds = calendar.component(.second, from: date as Date) print("\(hour):\(minutes):\(seconds)") 
 let date = Date() let units: Set<Calendar.Component> = [.hour, .day, .month, .year] let comps = Calendar.current.dateComponents(units, from: date) 

在Swift 3中你可以做到这一点,

 let date = Date() let hour = Calendar.current.component(.hour, from: date) 
 let hours = time / 3600 let minutes = (time / 60) % 60 let seconds = time % 60 return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds) 
 swift 4 ==> Getting iOS device current time:- print(" ---> ",(Calendar.current.component(.hour, from: Date())),":", (Calendar.current.component(.minute, from: Date())),":", (Calendar.current.component(.second, from: Date()))) output: ---> 10 : 11: 34