¿Cómo obtener la hora (hora, minuto, segundo) en Swift 3 usando NSDate?


Respuestas:


164

En Swift 3.0, Apple eliminó el prefijo 'NS' y simplificó todo. A continuación se muestra la forma de obtener la hora, los minutos y los segundos de la clase 'Fecha' (alternativa NSDate)

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)")

Como estos, puede obtener era, año, mes, fecha, etc. pasando correspondiente.


97

Swift 4.2 y 5

// *** Create date ***
let date = Date()

// *** create calendar object ***
var calendar = Calendar.current

// *** Get components using current Local & Timezone ***
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date))

// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone(identifier: "UTC")!

// *** Get All components from date ***
let components = calendar.dateComponents([.hour, .year, .minute], from: date)
print("All Components : \(components)")

// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")

Swift 3.0

// *** Create date ***
let date = Date()

// *** create calendar object ***
var calendar = NSCalendar.current

// *** Get components using current Local & Timezone ***    
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date))

// *** define calendar components to use as well Timezone to UTC ***
let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
calendar.timeZone = TimeZone(identifier: "UTC")!

// *** Get All components from date ***
let components = calendar.dateComponents(unitFlags, from: date)
print("All Components : \(components)")

// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")

Lo que si me da 'Component' is not a member type of 'Calendar'en la línea `let unitFlags ...` `
netigger

1
Lo que está preguntando no me queda claro, ¿cómo podría agregar el tipo de no miembro Calendar.Component? Considere que su fecha sigue a "02/12/15, 16:46" donde los segundos no están disponibles e intenta extraer los segundos usando Componentes; 0en ese caso , lo devolverá .
Dipen Panchasara

Encontré mi problema ... Había declarado una estructura nombrada Calendarque interfería Calendar.Componentobviamente.
netigger

25
let date = Date()       
let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
let comps = Calendar.current.dateComponents(units, from: date)

21

Rápido 4

    let calendar = Calendar.current
    let time=calendar.dateComponents([.hour,.minute,.second], from: Date())
    print("\(time.hour!):\(time.minute!):\(time.second!)")

19

En Swift 3 puedes hacer esto,

let date = Date()
let hour = Calendar.current.component(.hour, from: date)

definitivamente es la respuesta más concisa y simple)
Vlad

5
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)

5

Rápido 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)
    }
}

Uso:

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

4

Para mayor utilidad creo esta función:

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)"
}

Simplemente llámalo donde quieras así:

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

esta es la salida:

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

si quieres solo el tiempo simplemente cambia:

dateFormatter.dateFormat  = "HH:mm:ss"

y esta es la salida:

Date = 17:27:30

y eso es...


2
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

1

Esto puede resultar útil para quienes deseen utilizar la fecha actual en más de una clase.

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
}

}

Uso

        var time = ""
        time = time.getCurrentTime()
        print(time)   // 1900-12-09-12-59
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.