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

前端 未结 10 2577
孤独总比滥情好
孤独总比滥情好 2020-11-28 05:16

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

In Swift 2:

let date = NSDate()
let calendar = NSCalendar.currentCale         


        
10条回答
  •  無奈伤痛
    2020-11-28 05:55

    Swift 5+

    extension Date {
        
        func get(_ type: Calendar.Component)-> String {
            let calendar = Calendar.current
            let t = calendar.component(type, from: self)
            return (t < 10 ? "0\(t)" : t.description)
        }
    }
    

    Usage:

    print(Date().get(.year)) // => 2020
    print(Date().get(.month)) // => 08
    print(Date().get(.day)) // => 18 
    

提交回复
热议问题