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

前端 未结 10 2576
孤独总比滥情好
孤独总比滥情好 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:49

    For best useful I create this function:

    func dateFormatting() -> String {
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
        let mydt = dateFormatter.string(from: date).capitalized
    
        return "\(mydt)"
    }
    

    You simply call it wherever you want like this:

    print("Date = \(self.dateFormatting())")
    

    this is the Output:

    Date = Monday 15 October 2018 - 17:26:29
    

    if want only the time simply change :

    dateFormatter.dateFormat  = "HH:mm:ss"
    

    and this is the output:

    Date = 17:27:30
    

    and that's it...

提交回复
热议问题