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

前端 未结 10 2579
孤独总比滥情好
孤独总比滥情好 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条回答
  •  -上瘾入骨i
    2020-11-28 06:10

    This might be handy for those who want to use the current date in more than one class.

    extension String {
    
    
    func  getCurrentTime() -> String {
    
        let date = Date()
        let calendar = Calendar.current
    
    
        let year = calendar.component(.year, from: date)
        let month = calendar.component(.month, from: date)
        let day = calendar.component(.day, from: date)
        let hour = calendar.component(.hour, from: date)
        let minutes = calendar.component(.minute, from: date)
        let seconds = calendar.component(.second, from: date)
    
        let realTime = "\(year)-\(month)-\(day)-\(hour)-\(minutes)-\(seconds)"
    
        return realTime
    }
    
    }
    

    Usage

            var time = ""
            time = time.getCurrentTime()
            print(time)   // 1900-12-09-12-59
    

提交回复
热议问题