2015-11-02 17 views
7

Mi piacciono le date della stringa UTC che assomigliano a questo "2015-10-17T00: 00: 00.000Z" e voglio convertirle in un NSDate in questo formato "Ottobre 12th 2015 11:19:12 "Come convertire una stringa di data UTC in NSDate in Swift

Questo è il percorso che sto cercando ma non riesco a trovare la data giusta Formattazione.

let dateFormatter = NSDateFormatter() 
dateFormatter.dateFormat = //can't seem to get this right 
dateFormatter.timeZone = NSTimeZone(name: "UTC") 
let date = dateFormatter.dateFromString("2015-10-17T00:00:00.000Z") 
+2

Possibile duplicato di [Conversione di un ISO 8601 timestamp in un NSDate: come si gestisce l'offset dell'ora UTC?] (Http://stackoverflow.com/questions/5185230/converting-an-iso-8601-timestamp-into-an-nsdate-how-does-one-deal- with-the-utc) –

+0

Nessuna delle risposte elencate funziona per me per qualche motivo – jonv562

risposta

15

penso che questo dovrebbe funzionare

let formatter = NSDateFormatter() 
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
let localDate = formatter.dateFromString(date) 
+0

Questa era una parte della risposta, ma la data che ottengo non è nel formato corretto, ma se si applica un nuovo formato a questo NSDate e lo si cambia in una stringa funziona formatter.dateFormat = "MMMM d 'a' h: mm a" var dateString = formatter.stringFromDate (localDate!) – jonv562

+0

Ok fantastico sì, ho dimenticato di dirlo. Oppure puoi creare un nuovo oggetto DataFormatter() per recuperare la data nel formato richiesto. – ozzyzig

+0

ottima risposta, ha risolto il mio problema –

3

Questo funziona per Swift 3.0 e ultima Xcode [aprile 2017]

let dateString = "2017-Jan-01 12:00:00.250" 
     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "yyyy-M-dd HH:mm:ss.SSS" 
     dateFormatter.locale = Locale.init(identifier: "en_GB") 
     let dateObj = dateFormatter.date(from: dateString) 

     let date = dateObj 
     let formatter = DateFormatter() 
     formatter.calendar = Calendar(identifier: .iso8601) 
     formatter.locale = Locale(identifier: "en_US_POSIX") 
     formatter.timeZone = TimeZone(secondsFromGMT: 0) 
     formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSXXXXX" 
     let currentDateTime = formatter.string(from: date!) 
Problemi correlati