Convertir NSDate a Cadena en iOS Swift [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Estoy tratando de convertir un NSDate a un String y luego Cambiar el Formato. Pero cuando paso NSDate a String está produciendo espacios en blanco.

 let formatter = DateFormatter()
 let myString = (String(describing: date))
 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
 let yourDate: Date? = formatter.date(from: myString)
 formatter.dateFormat = "dd-MMM-yyyy"
 print(yourDate)
Author: RichAppz, 2017-03-01

7 answers

Obtendrá la información detallada de Documento de Apple Dateformatter.Si desea establecer la dateformat para su dateString, ver este link , el detalle dateformat usted puede conseguir aquí por ejemplo , hacer como

let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let myString = formatter.string(from: Date()) // string purpose I add here 
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)

print(myStringafd)

Se obtiene la salida como

introduzca la descripción de la imagen aquí

 93
Author: Anbu.karthik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-01 10:55:05

Siempre uso este código al convertir Date a String. (Swift 3)

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

}

Y llama así . .

let today = Date()
today.toString(dateFormat: "dd-MM")
 34
Author: roy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-10 06:30:08

Su código actualizado.actualízalo.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)
 4
Author: Brijesh Shiroya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-01 06:34:09

DateFormatter tiene algunos estilos de fecha de fábrica para aquellos demasiado perezosos para jugar con cadenas de formato. Si no necesitas un estilo personalizado, aquí tienes otra opción:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

Esto le da los siguientes estilos:

short, medium, long, full

Ejemplo de uso:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18
 3
Author: Adrian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-10 13:47:07

Algo a tener en cuenta al crear formateadores es intentar reutilizar la misma instancia si puede, ya que los formateadores son bastante costosos de crear computacionalmente. El siguiente es un patrón que uso con frecuencia para aplicaciones donde puedo compartir el mismo formateador en toda la aplicación, adaptado de NSHipster .

extension DateFormatter {

    static var sharedDateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()   
        // Add your formatter configuration here     
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return dateFormatter
    }()
}

Uso:

let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
 2
Author: Kevin Stewart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-30 19:25:16

Puede usar esta extensión:

extension Date {

    func toString(withFormat format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        let myString = formatter.string(from: self)
        let yourDate = formatter.date(from: myString)
        formatter.dateFormat = format

        return formatter.string(from: yourDate!)
    }
}

Y úselo en su controlador de vista de esta manera (reemplace con su formato):

yourString = yourDate.toString(withFormat: "yyyy")
 1
Author: Archi Stepanov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-17 13:06:50

Después de asignar DateFormatter debe dar la cadena formateada a continuación, puede convertir como cadena de esta manera

var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)

Salida

01-Mar-2017

 0
Author: jignesh Vadadoriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-01 06:41:34