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

前端 未结 10 2502
孤独总比滥情好
孤独总比滥情好 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:48
    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
    
    0 讨论(0)
  • 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...

    0 讨论(0)
  • 2020-11-28 05:51

    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.

    0 讨论(0)
  • 2020-11-28 05:51
    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)
    
    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 2020-11-28 06:01
    let date = Date()       
    let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
    let comps = Calendar.current.dateComponents(units, from: date)
    
    0 讨论(0)
提交回复
热议问题