Formato de fecha en Swift


150

¿Cómo convertiré esta fecha y hora desde la fecha?

De esto: 2016-02-29 12:24:26
a: 29 de febrero de 2016

Hasta ahora, este es mi código y devuelve un valor nulo:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date: NSDate? = dateFormatter.dateFromString("2016-02-29 12:24:26")
print(date)

Respuestas:


267

Debe declarar 2 diferentes NSDateFormatters, el primero para convertir la cadena a ay NSDateel segundo para imprimir la fecha en su formato.
Prueba este código:

let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))

Swift 3 y superior:

Desde Swift 3, la NSDateclase ha cambiado a Datey NSDateFormatterpara DateFormatter.

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
    print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}

1
¿Qué sucede si dateFormatterGet dateFormat necesita aceptar 2 formatos diferentes, uno con milisegundos y otro sin milisegundos? es decir, aaaa-MM-dd'T'HH: mm: ssZZZZZ y aaaa-MM-dd'T'HH: mm: ss: SSSZZZZZ
— KvnH

1
Creo que debe declarar dos DateFormatters diferentes para obtener la fecha: si el primero falla (devolverá cero), use el segundo.
— LorenzOliveto

¿Me pueden ayudar, cuál será el formato de fecha para "Mar 12 de marzo de 2019 12:00:00 GMT-0500 (CDT)"
— Devesh

@Devesh debería ser algo como esto "EEE MMM d aaaa HH: mm: ss ZZZZ", echa un vistazo a nsdateformatter.com es un sitio muy útil con todos los formatos compatibles
— LorenzOliveto

@lorenzoliveto sí, he intentado todo el camino para este formato. También probé en nsdateformatter.com, aún así, no puedo obtener nada para "Mar 12 mar 2019 12:00:00 GMT-0500 (CDT)" este formato. Estoy obteniendo este formato en un JSON. No estoy seguro de si se trata de una cadena válida, ¿pueden ayudarme?
— Devesh

212

Esto puede ser útil para quienes desean usar dateformater.dateformat; si quieres 12.09.18usasdateformater.dateformat = "dd.MM.yy"

Wednesday, Sep 12, 2018           --> EEEE, MMM d, yyyy
09/12/2018                        --> MM/dd/yyyy
09-12-2018 14:11                  --> MM-dd-yyyy HH:mm
Sep 12, 2:11 PM                   --> MMM d, h:mm a
September 2018                    --> MMMM yyyy
Sep 12, 2018                      --> MMM d, yyyy
Wed, 12 Sep 2018 14:11:54 +0000   --> E, d MMM yyyy HH:mm:ss Z
2018-09-12T14:11:54+0000          --> yyyy-MM-dd'T'HH:mm:ssZ
12.09.18                          --> dd.MM.yy
10:41:02.112                      --> HH:mm:ss.SSS

2
Su respuesta ha sido muy esclarecedora y solucionó mi problema. Gracias.
— andrewcar

50

Swift 3 y superior

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.locale = Locale(identifier: "en_US")
print(dateFormatter.string(from: date)) // Jan 2, 2001

Esto también es útil cuando desea localizar su aplicación. La configuración regional (identificador :) utiliza el código ISO 639-1 . Ver también la documentación de Apple


8
Si desea localizar su aplicación, solo use Locale.currentla configuración regional del usuario.
— Victor Engel

46

Swift - 5.0

let date = Date()
let formate = date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss") // Set output formate

extension Date {
   func getFormattedDate(format: String) -> String {
        let dateformat = DateFormatter()
        dateformat.dateFormat = format
        return dateformat.string(from: self)
    }
}

Swift - 4.0

2018-02-01T19: 10: 04 + 00: 00 Convertir febrero 01,2018

extension Date {
    static func getFormattedDate(string: String , formatter:String) -> String{
        let dateFormatterGet = DateFormatter()
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

        let dateFormatterPrint = DateFormatter()
        dateFormatterPrint.dateFormat = "MMM dd,yyyy"

        let date: Date? = dateFormatterGet.date(from: "2018-02-01T19:10:04+00:00")
        print("Date",dateFormatterPrint.string(from: date!)) // Feb 01,2018
        return dateFormatterPrint.string(from: date!);
    }
}

36

Versión Swift 3 con el nuevo Dateobjeto en su lugar NSDate:

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy"

let date: Date? = dateFormatterGet.date(from: "2017-02-14 17:24:26")
print(dateFormatter.string(from: date!))

EDITAR: después de la sugerencia de mitul-nakum


2
dateFormatterGet.dateFormat = "aaaa-MM-dd HH: mm: ss" el formato de hora requerirá HH mayúscula, ya que la hora está en formato 24
— Mitul Nakum

22

rápido 3

let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)

16

yyyy-MM-dd'T'HH:mm:ss.SSS'Z'Resolví mi problema al formato (por ejemplo, 2018-06-15T00: 00: 00.000Z) con esto:

func formatDate(date: String) -> String {
   let dateFormatterGet = DateFormatter()
   dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

   let dateFormatter = DateFormatter()
   dateFormatter.dateStyle = .medium
   dateFormatter.timeStyle = .none
   //    dateFormatter.locale = Locale(identifier: "en_US") //uncomment if you don't want to get the system default format.

   let dateObj: Date? = dateFormatterGet.date(from: date)

   return dateFormatter.string(from: dateObj!)
}

9

Swift 3 con una Dateextensión

extension Date {
    func string(with format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

Entonces puedes usarlo así:

let date = Date()
date.string(with: "MMM dd, yyyy")

8

Swift 4, 4.2 y 5

func getFormattedDate(date: Date, format: String) -> String {
        let dateformat = DateFormatter()
        dateformat.dateFormat = format
        return dateformat.string(from: date)
}

let formatingDate = getFormattedDate(date: Date(), format: "dd-MMM-yyyy")
        print(formatingDate)

1
¡Esta es una buena solución corta con solo una DateFormatter()! Algo a tener en cuenta: ¡ DateFormattertambién tiene en cuenta la región de aplicación (establecida en el esquema)! Por ejemplo, 2019-05-27 11:03:03 +0000con el formato yyyy-MM-dd HH:mm:ssy "Alemania" a medida que la región se convierte 2019-05-27 13:03:03. Esta diferencia es causada por el horario de verano: en verano, Alemania es GMT + 2, mientras que en invierno es GMT + 1.
— Neph

4

Si desea analizar la fecha de "1996-12-19T16: 39: 57-08: 00", utilice el siguiente formato "aaaa-MM-dd'T'HH: mm: ssZZZZZ":

let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.date(from: string)

de Apple https://developer.apple.com/documentation/foundation/dateformatter


3

Otra interesante posibilidad de formato de fecha. Esta captura de pantalla pertenece a la aplicación de Apple "Noticias".

Captura de pantalla de la aplicación

Aquí está el código:

let dateFormat1 = DateFormatter()
dateFormat1.dateFormat = "EEEE"
let stringDay = dateFormat1.string(from: Date())

let dateFormat2 = DateFormatter()
dateFormat2.dateFormat = "MMMM"
let stringMonth = dateFormat2.string(from: Date())

let dateFormat3 = DateFormatter()
dateFormat3.dateFormat = "dd"
let numDay = dateFormat3.string(from: Date())

let stringDate = String(format: "%@\n%@ %@", stringDay.uppercased(), stringMonth.uppercased(), numDay)

Nada que agregar a la alternativa propuesta por lorenzoliveto. Es perfecto

let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEEE\nMMMM dd"
let stringDate = dateFormat.string(from: Date()).uppercased()

Esto se puede compactar usando solo un formateador de fecha con el formato "EEEE \ nMMMM dd".
— LorenzOliveto

Gracias. No conocía esta sintaxis. ¡Muy útil! ¡Muchas gracias!
— Markus

RECTIFICACIÓN: He probado el código pero no obtienes las letras en mayúscula.
— Markus el

1
Sí, la mayúscula debe aplicarse a la cadena devuelta, como en su respuesta. El formateador de la fecha no devuelve una cadena en mayúscula. Simplemente agregue .uppercased () como este "dateFormat.string (from: Date ()).
— Uppercased

3
    import UIKit
    // Example iso date time
    let isoDateArray = [
        "2020-03-18T07:32:39.88Z",
        "2020-03-18T07:32:39Z",
        "2020-03-18T07:32:39.8Z",
        "2020-03-18T07:32:39.88Z",
        "2020-03-18T07:32:39.8834Z"
    ]


    let dateFormatterGetWithMs = DateFormatter()
    let dateFormatterGetNoMs = DateFormatter()

// Formater with and without millisecond 
    dateFormatterGetWithMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    dateFormatterGetNoMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "MMM dd,yyyy"

    for dateString in isoDateArray {
        var date: Date? = dateFormatterGetWithMs.date(from: dateString)
        if (date == nil){
            date = dateFormatterGetNoMs.date(from: dateString)
        }
        print("===========>",date!)
    }

Si bien este código puede responder la pregunta, proporcionar un contexto adicional con respecto a cómo y / o por qué resuelve el problema mejoraría el valor a largo plazo de la respuesta.
— Piotr Labunski

2

Para convertir 2016-02-29 12:24:26 en una fecha, use este formateador de fecha:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

Editar: Para obtener la salida el 29 de febrero de 2016, use este formateador de fecha:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"

Pero, ¿cómo va a convertir eso a este tipo de formato de fecha 29 de febrero de 2016
— Sydney Loteria

¿Sabes por qué me sale nada cuando intento imprimir esto?
— Pavlos

2

solo use la siguiente función para convertir el formato de fecha: -

  let convertedFormat =  convertToString(dateString: "2019-02-12 11:23:12", formatIn: "yyyy-MM-dd hh:mm:ss", formatOut: "MMM dd, yyyy")    //calling function

   print(convertedFormat) // feb 12 2019


 func convertToString (dateString: String, formatIn : String, formatOut : String) -> String {

    let dateFormater = DateFormatter()
    dateFormater.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
    dateFormater.dateFormat = formatIn
    let date = dateFormater.date(from: dateString)

    dateFormater.timeZone = NSTimeZone.system

    dateFormater.dateFormat = formatOut
    let timeStr = dateFormater.string(from: date!)
    return timeStr
 }

1

Para Swift 4.2, 5

Pase la fecha y el formato de la forma que desee. Para elegir el formato que puede visitar, el sitio web NSDATEFORMATTER :

static func dateFormatter(date: Date,dateFormat:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    return dateFormatter.string(from: date)
}

0

rápido 3

func dataFormat(dataJ: Double) -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .none
        let date = Date(timeIntervalSince1970: dataJ)
        return (dataJ != nil) ? "Today, \(dateFormatter.string(from: date))" : "Date Invalid"

    }

0

Colóquelo en extensión y llámelo como a continuación. Es fácil de usar en toda la aplicación.

self.getFormattedDate(strDate: "20-March-2019", currentFomat: "dd-MMM-yyyy", expectedFromat: "yyyy-MM-dd")

Implementación

func getFormattedDate(strDate: String , currentFomat:String, expectedFromat: String) -> String{
        let dateFormatterGet = DateFormatter()
        dateFormatterGet.dateFormat = currentFomat

        let date : Date = dateFormatterGet.date(from: strDate)!

        dateFormatterGet.dateFormat = expectedFromat
        return dateFormatterGet.string(from: date)
    }

0

Recomiendo agregar zona horaria por defecto. Mostraré un ejemplo para swift 5
1. nuevo un archivo de extensiónDate+Formatter.swift

import Foundation

extension Date {
    func getFormattedDateString(format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.timeZone = TimeZone.current
        return dateFormatter.string(from: self)
    }
}
  1. Ejemplo de uso
    let date = Date()
    let dateString = date.getFormattedDateString(format: "yyyy-MM-dd HH:mm:ss")
    print("dateString > \(dateString)")
    // print
    // dateString > 2020-04-30 15:15:21
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.