Como posso converter a data da string em NSDate?


195

Quero converter "2014-07-15 06: 55: 14.198000 + 00: 00" nesta data da cadeia de caracteres para NSDate no Swift.


Parece que sua string "2014/07/15 06: 55: 14.198000 + 00: 00" não é alcançável se você usar NSDateFormatter
— Alex Peda


Como um recurso complementar para todas as respostas abaixo, eu recomendo verificar nsdateformatter.com
— user3344977

As respostas antigas aqui são realmente ERRADAS . O documento da Apple diz claramente que você precisa armazenar em cache o formatador. stackoverflow.com/a/42370648/294884
— Fattie

Se você precisar de algum ajudante com o formato, nsdateformatter.com
— Pedro Luz

Respostas:


341

tente isto:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)

Para consultas adicionais, verifique as classes NSDateFormatter e DateFormatter da estrutura Foundation para Objective-C e Swift, respectivamente.

Swift 3 e posterior (Swift 4 incluído)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
guard let date = dateFormatter.date(from: /* your_date_string */) else {
   fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here

11
Encontrou a solução só precisa definir "hh AAAA-MM-DD: MM: ss.SSSSxxx" Este formato de data
— Shardul

1
Eu tenho uma string de data como esta "2014-07-15 06: 55: 14-0400" e tentei usar yyyy-MM-dd hh:mm:ssZZZ. Mas não consigo tirar o objeto de data da string.
— Iamprem 06/04

2
@Prem, se você ver que a saída está "2014-07-15 10:55:14 +0000"correta. A partir da NSDatedescrição, a saída da data seria calculada com diferença (aqui, GMT -4 horas). Se você quiser obter a diferença entre GMT e UTC, -0400verifique esta referência
— x4h1d 07/04

@ x4h1d, ei, entendi! Eu cometi um erro em hhque deveria estar HH. Obrigado!
— Iamprem 07/04

3
@ lmiguelvargasf, acho que seria yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. Eu assumi que Zé apenas um personagem aqui. Lembre-se, também Ztem um significado especial. Se você deseja Zespecificar como basic hmso formato seria yyyy-MM-dd'T'HH:mm:ss.SSSZ.
— X4h1d 02/10/2015

71

Swift 4

import Foundation

let dateString = "2014-07-15" // change to your date format

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let date = dateFormatter.date(from: dateString)
println(date)

Swift 3

import Foundation

var dateString = "2014-07-15" // change to your date format

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

var date = dateFormatter.dateFromString(dateString)
println(date)

Eu posso fazer isso com este código.


5
O código não está certo. Ele gera alguns "15 de janeiro de 2014, 00:00"
— Jake Lin

5
usar em ddvez de DDdeve ajudar a corrigir o problema "sempre em janeiro".
— Pascal Belloncle

1
A versão correta é, yyyy-MM-ddcaso contrário, a data da análise será bloqueada em janeiro - atualizei a resposta para refletir a alteração.
— Zorayr

E se eu quiser passar a data atual como string. Isso vai funcionar?
— Arjun Kalidas #

@Zorayr, Kittisak: Estou obtendo o resultado final, Opcional (2014-07-14 18:30:00 +0000), significa que um dia é diminuído. Como posso consertar isso ?
— Vineesh TP

54
 func convertDateFormatter(date: String) -> String
 {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let date = dateFormatter.dateFromString(date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date!)


    return timeStamp
}

Atualizado para o Swift 3.

func convertDateFormatter(date: String) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: date!)


    return timeStamp
}

17

Detalhes

  • Swift 4, Xcode 9.2
  • Swift 5, Xcode 10.2 (10E125)

Solução

import Foundation

extension DateFormatter {

    convenience init (format: String) {
        self.init()
        dateFormat = format
        locale = Locale.current
    }
}

extension String {

    func toDate (dateFormatter: DateFormatter) -> Date? {
        return dateFormatter.date(from: self)
    }

    func toDateString (dateFormatter: DateFormatter, outputFormat: String) -> String? {
        guard let date = toDate(dateFormatter: dateFormatter) else { return nil }
        return DateFormatter(format: outputFormat).string(from: date)
    }
}

extension Date {

    func toString (dateFormatter: DateFormatter) -> String? {
        return dateFormatter.string(from: self)
    }
}

Uso

var dateString = "14.01.2017T14:54:00"
let dateFormatter = DateFormatter(format: "dd.MM.yyyy'T'HH:mm:ss")
let date = Date()

print("original String with date:               \(dateString)")
print("date String() to Date():                 \(dateString.toDate(dateFormatter: dateFormatter)!)")
print("date String() to formated date String(): \(dateString.toDateString(dateFormatter: dateFormatter, outputFormat: "dd MMMM")!)")
let dateFormatter2 = DateFormatter(format: "dd MMM HH:mm")
print("format Date():                           \(date.toString(dateFormatter: dateFormatter2)!)")

Resultado

insira a descrição da imagem aqui

Mais Informações

Sobre o formato da data


15

Se você precisar analisar a sequência em uma data frequentemente, convém mover a funcionalidade para uma extensão. Criei um arquivo sharedCode.swift e coloquei minhas extensões lá:

extension String
{   
    func toDateTime() -> NSDate
    {
        //Create Date Formatter
        let dateFormatter = NSDateFormatter()

        //Specify Format of String to Parse
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"

        //Parse into NSDate
        let dateFromString : NSDate = dateFormatter.dateFromString(self)!

        //Return Parsed Date
        return dateFromString
    }
}

Então, se você deseja converter sua string em um NSDate, basta escrever algo como:

var myDate = myDateString.toDateTime()

1
Obrigado. Também é possível, embora menos útil, escrever: var myDate = "04-05-2015" .toDateTime () Achei isso útil ao configurar dados de teste.
— Stephen Watson

1
Tenho certeza de que o hhdeve ser HHneste caso.
— 25416 Alex

Isso não me fornece o formato especificado: var date = NSDate (); deixe dateFormatter = NSDateFormatter (); dateFormatter.dateFormat = "MMMM d, AAAA"; deixe myDate = dateFormatter.stringFromDate (date); Além disso, se eu usar sua extensão assim -> var myDate2 = myDate.toDateTime (); Está me dando uma data totalmente diferente e não a data atual.
— Arjun Kalidas #

9

Para Swift 3

func stringToDate(_ str: String)->Date{
    let formatter = DateFormatter()
    formatter.dateFormat="yyyy-MM-dd hh:mm:ss Z"
    return formatter.date(from: str)!
}
func dateToString(_ str: Date)->String{
    var dateFormatter = DateFormatter()
    dateFormatter.timeStyle=DateFormatter.Style.short
    return dateFormatter.string(from: str)
}

5

Os fragmentos de código nesta página do controle de qualidade estão "de cabeça para baixo" ...

A primeira coisa que a Apple menciona é que você armazena em cache o formatador ...

Link para o documento da Apple, indicando exatamente como fazer isso:

Formatadores de cache para eficiência Criar um formatador de datas não é uma operação barata. ... armazenar em cache uma única instância ...

Use um ...

let df : DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    return formatter 
}()

Em seguida, basta usar esse formatador em qualquer lugar ...

let s = df.string(from: someDate)

ou

let d = df.date(from: someString)

Ou use qualquer um dos outros métodos convenientes no DateFormatter.

É simples assim.

(Se você escrever uma extensão em String, seu código estará completamente "invertido" - você não poderá usar nenhuma chamada dateFormatter!)

Observe que geralmente você terá alguns desses globais .. como "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" ... etc.


Não há necessidade de deixá-los no escopo global. Você pode estender o Formatador apenas declarando suas propriedades estáticas. verifique este stackoverflow.com/a/43658213/2303865
— Leo Dabus

4

Extensões de apoio Swift, com extensão você pode adicionar uma nova funcionalidade a um já existente class, structure, enumeration, ou protocoltipo.

Você pode adicionar uma nova initfunção ao NSDateobjeto extendendo o objeto usando a extensionpalavra - chave.

extension NSDate
{
    convenience
    init(dateString:String) {
        let dateStringFormatter = NSDateFormatter()
        dateStringFormatter.dateFormat = "yyyyMMdd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "fr_CH_POSIX")
        let d = dateStringFormatter.dateFromString(dateString)!
        self.init(timeInterval:0, sinceDate:d)
    }
} 

Agora você pode iniciar um objeto NSDate usando:

let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")

Eu gosto do jeito init. Não existe outra maneira de criar a data sem usar timeInterval? e se o nsdate parar de ter um inicializador com um parâmetro de data? como você resolveria isso? Pessoalmente eu prefiro uma forma de inicialização, mas eu não sei como superar este problema
— Mijail

Eu tenho um problema: minha data como string é assim: "2017-03-10 22:16:00 +0000" e usei este formato: "aaaa-MM-dd hh: mm: ss Z" e este: "aaaa-MM-dd'T'HH: mm: ss". Mas para ambos, quando faço isso: deixe beginDate = df.date(from: beginDateString), recebo um valor nulo! porque? ( df = DateFormatter())
— Paul Bénéteau

4

Desde o Swift 3, muitos dos prefixos NS foram eliminados.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
/* date format string rules
 * http://userguide.icu-project.org/formatparse/datetime
 */

let date = dateFormatter.date(from: dateString)

Eu tenho um problema: minha data como string é assim: "2017-03-10 22:16:00 +0000" e usei este formato: "aaaa-MM-dd hh: mm: ss Z" e este: "aaaa-MM-dd'T'HH: mm: ss". Mas para ambos, quando faço isso: deixe beginDate = df.date(from: beginDateString), recebo um valor nulo! porque? ( df = DateFormatter())
— Paul Bénéteau

4

Swift 3,4:

2 conversões úteis:

string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date

Uso: 1.

let date = Date() //gives today's date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let todaysDateInUKFormat = dateFormatter.string(from: date)

2)

 let someDateInString = "23.06.2017"
 var getDateFromString = dateFormatter.date(from: someDateInString)

3

PARA SWIFT 3.1

func convertDateStringToDate(longDate: String) -> String{

    /* INPUT: longDate = "2017-01-27T05:00:00.000Z"
     * OUTPUT: "1/26/17"
     * date_format_you_want_in_string from
     * http://userguide.icu-project.org/formatparse/datetime
     */

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let date = dateFormatter.date(from: longDate)

    if date != nil {

        let formatter = DateFormatter()
        formatter.dateStyle = .short
        let dateShort = formatter.string(from: date!)

        return dateShort

    } else {

        return longDate

    }
}

NOTA: ISTO RETORNARÁ A CORDA ORIGINAL SE ERRO


2

Para adicionar String no formato de data no Swift, fiz isso

 var dataFormatter:NSDateFormatter = NSDateFormatter()
                dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"

cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)

2

Este trabalho para mim ..

    import Foundation
    import UIKit

    //dateString = "01/07/2017"
    private func parseDate(_ dateStr: String) -> String {
            let simpleDateFormat = DateFormatter()
            simpleDateFormat.dateFormat = "dd/MM/yyyy" //format our date String
            let dateFormat = DateFormatter()
            dateFormat.dateFormat = "dd 'de' MMMM 'de' yyyy" //format return

            let date = simpleDateFormat.date(from: dateStr)
            return dateFormat.string(from: date!)
    }

1

Abaixo estão algumas opções de conversão de formato de string para data que podem ser usadas no iOS rápido.

  1. Thursday, Dec 27, 2018 format = EEEE, MMM d, yyyy
  2. 12/27/2018 format = MM/dd/yyyy
  3. 12-27-2018 09:59 format = MM-dd-yyyy HH:mm
  4. Dec 27, 9:59 AM format = MMM d, h:mm a
  5. December 2018 format = MMMM yyyy
  6. Dec 27, 2018 format = MMM d, yyyy
  7. Thu, 27 Dec 2018 09:59:19 +0000 format = E, d MMM yyyy HH:mm:ss Z
  8. 2018-12-27T09:59:19+0000 format = yyyy-MM-dd'T'HH:mm:ssZ
  9. 27.12.18 format = dd.MM.yy
  10. 09:59:19.815 format = HH:mm:ss.SSS

0
Swift: iOS
if we have string, convert it to NSDate,

var dataString = profileValue["dob"] as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"

// convert string into date
let dateValue:NSDate? = dateFormatter.dateFromString(dataString)

if you have and date picker parse date like this

// to avoid any nil value
if let isDate = dateValue {
self.datePicker.date = isDate
}

0

Você pode tentar este código rápido

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"//same as strDate date formator
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")//Must used if you get one day less in conversion
    let convertedDateObject = dateFormatter.date(from: strDate)

0

SWIFT 5 , Xcode 11.0

Passe sua (data na sequência) em "dateString" e no formato de passagem "dateFormat" desejado. Para escolher o formato, use o site NDateFormatter .

func getDateFrom(dateString: String, dateFormat: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    dateFormatter.locale = Locale(identifier: "en_US")
    guard let date = dateFormatter.date(from: dateString) else {return nil}
    return date
}

-3
import Foundation

let now : String = "2014-07-16 03:03:34 PDT"
var date : NSDate
var dateFormatter : NSDateFormatter

date = dateFormatter.dateFromString(now)

date // $R6: __NSDate = 2014-07-16 03:03:34 PDT

https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/doc/uid/20000447-SW32


2
Como é que isso deveria funcionar? O formatador de data não é inicializado e também não há motivo para dividir a declaração e a inicialização da data.
— Ixx
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.