Formato data in Swift


150

Come posso convertire questo datetime dalla data?

Da questo: 29-02-2016 12:24:26
a: 29 febbraio 2016

Finora, questo è il mio codice e restituisce un valore nullo:

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)

Risposte:


267

Devi dichiarare 2 differenti NSDateFormatters, il primo per convertire la stringa in a NSDatee il secondo per stampare la data nel tuo formato.
Prova questo codice:

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 e versioni successive:

Da Swift 3 la NSDateclasse è stata modificata in Datee NSDateFormatterin 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
Cosa succede se dateFormatterGet dateFormat deve accettare 2 formati diversi: uno contenente millisecondi e uno senza millisecondi? cioè yyyy-MM-dd'T'HH: mm: ssZZZZZ e yyyy-MM-dd'T'HH: mm: ss: SSSZZZZZ
— KvnH

1
Penso che tu debba dichiarare due DateFormatters diversi per ottenere la data: se il primo fallisce (restituirà zero), usa il secondo.
— LorenzOliveto,

Potete per favore aiutarmi, quale sarà il formato della data per "mar 12 2019 12:00:00 GMT-0500 (CDT)"
— Devesh

@Devesh dovrebbe essere qualcosa del genere "EEE MMM d yyyy HH: mm: ss ZZZZ", controlla nsdateformatter.com è un sito molto utile con tutti i formati supportati
— LorenzOliveto

@lorenzoliveto sì, ho provato fino in fondo per questo formato. Ho provato anche su nsdateformatter.com, tuttavia, non riesco a ottenere nulla per "Mar 12 2019 2019 12:00:00 GMT-0500 (CDT)" in questo formato. Ricevo questo formato in un JSON. Non sono sicuro che questa sia una stringa valida, puoi aiutarmi, per favore.
— Devesh,

212

Questo può essere utile per chi desidera utilizzare dateformater.dateformat; se vuoi 12.09.18usarlodateformater.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
La tua risposta è stata così illuminante e risolto il mio problema. Grazie.
— Andrewcar,

50

Swift 3 e versioni successive

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

Questo è utile anche quando vuoi localizzare la tua app. Le impostazioni internazionali (identificatore :) utilizzano il codice ISO 639-1 . Vedi anche la documentazione Apple


8
Se vuoi localizzare la tua app, usa solo Locale.currentper usare la localizzazione dell'utente.
— 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

01/02/2018T19: 10: 04 + 00: 00 Conversione febbraio 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

Swift 3 versione con il nuovo Dateoggetto invece 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!))

EDIT: dopo il suggerimento mitul-nakum


2
dateFormatterGet.dateFormat = "yyyy-MM-dd HH: mm: ss" ora il formato richiede capitale HH, poiché l'ora è in formato 24
— Mitul Nakum,

22

veloce 3

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

16

Ho risolto il mio problema con il formato yyyy-MM-dd'T'HH:mm:ss.SSS'Z'(ad esempio 2018-06-15T00: 00: 00.000Z) con questo:

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 Dateun'estensione

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

Quindi puoi usarlo in questo modo:

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

8

Swift 4, 4.2 e 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
Questa è una buona soluzione breve con un solo DateFormatter()! Qualcosa da tenere presente: DateFormatterprende in considerazione anche l'area dell'applicazione (impostata nello schema)! Ad esempio 2019-05-27 11:03:03 +0000con il formato yyyy-MM-dd HH:mm:sse "Germania" come la regione si trasforma in 2019-05-27 13:03:03. Questa differenza è causata dall'ora legale: in estate la Germania è GMT + 2, mentre in inverno è GMT + 1.
— Neph,

4

Se si desidera analizzare la data da "1996-12-19T16: 39: 57-08: 00", utilizzare il seguente formato "yyyy-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)

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


3

Un'altra possibilità interessante di data formato. Questo screenshot appartiene all'App di Apple "Novità".

Schermata dell'app

Ecco il codice:

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)

Nulla da aggiungere all'alternativa proposta da Lorenzoliveto. È semplicemente perfetto

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

Questo può essere compattato usando solo un formattatore di data con il formato "EEEE \ nMMMM dd".
— Lorenz Oliveto,

Grazie. Non conoscevo questa sintassi. Molto utile! Grazie mille!
— Markus,

RETTIFICA: Ho testato il codice ma non ottieni le lettere maiuscole.
— Markus,

1
Sì, la maiuscola deve essere applicata alla stringa restituita, come nella tua risposta. Il formatter data non restituisce una stringa maiuscola. Aggiungi .uppercased () come questo "dateFormat.string (da: 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!)
    }

Sebbene questo codice possa rispondere alla domanda, fornire un contesto aggiuntivo riguardo a come e / o perché risolve il problema migliorerebbe il valore a lungo termine della risposta.
— Piotr Labunski il

2

Per convertire il 29/02/2016 12:24:26 in una data, usa questo formatter data:

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

Modifica: per ottenere l'output del 29 febbraio 2016 utilizzare questo formatter data:

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

Ma come lo convertirai in questo tipo di formato data 29 febbraio 2016
— Sydney Loteria,

sai perché ottengo nulla quando provo a stampare questo?
— Pavlos,

2

basta usare la funzione seguente per convertire il formato della data: -

  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

Per Swift 4.2, 5

Passa la data e il formato come preferisci. Per scegliere il formato che puoi visitare, il sito Web NSDATEFORMATTER :

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

0

veloce 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

Mettilo nell'estensione e chiamalo come sotto. È facile da usare in tutta l'applicazione.

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

Implementazione

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

Consiglio di aggiungere il fuso orario per impostazione predefinita. Mostrerò un esempio di swift 5
1. nuovo un file di estensioneDate+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. Esempio di utilizzo
    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
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.