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

2020-01-26 05:28发布

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?

标签: nsdate swift3
9条回答
做个烂人
2楼-- · 2020-01-26 05:54

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.

查看更多
Rolldiameter
3楼-- · 2020-01-26 05:59

In Swift 3 you can do this,

let date = Date()
let hour = Calendar.current.component(.hour, from: date)
查看更多
\"骚年 ilove
4楼-- · 2020-01-26 06:02
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
查看更多
登录 后发表回答