How to convert a String to Date on Swift

Asked

Viewed 1,761 times

0

i receive the date as follows 2016-08-14T20:38:27.031-03:00 as string, I would like to pass to date on the standard dd/MM/yyyy, I have already searched the net some solutions however were not useful

3 answers

3


For this date format 2016-08-14T20:38:27.031-03:00 iso8601, Voce needs to use the following format with thousandth of seconds SSS and XXX for time zone (-03:00 or Z):

"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"

Xcode 8 Beta 6 • Swift 3

extension Date {
    struct Formatter {
        static let iso8601: DateFormatter = {
            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'T'HH:mm:ss.SSSXXX"
            return formatter
        }()
    }
    var iso8601: String { return Formatter.iso8601.string(from: self) }
}

extension String {
    var dateFromISO8601: Date? {
        return Date.Formatter.iso8601.date(from: self)
    }
}

Date() // "Aug 18, 2016, 8:09 PM"
let dateString = Date().iso8601  // "2016-08-18T23:09:59.830Z"
print(dateString) //  "2016-08-18T23:09:59.830Z\n"

if let dateFromString = dateString.dateFromISO8601 {
    print(dateFromString)   // "2016-08-18 23:09:59 +0000\n"
    print(dateFromString.iso8601)  // "2016-08-18T23:09:59.830Z"
}

Xcode 7.3.1 • Swift 2.2.1

extension NSDate {
    struct Formatter {
        static let iso8601: NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
            formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
            formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
            return formatter
        }()
    }
    var iso8601: String { return Formatter.iso8601.stringFromDate(self) }
}

extension String {
    var dateFromISO8601: NSDate? {
        return NSDate.Formatter.iso8601.dateFromString(self)
    }
}

NSDate() // "Aug 19, 2016, 1:49 AM"
let dateString = NSDate().iso8601  // "2016-08-19T04:49:35.792Z"
print(dateString) //  "2016-08-19T04:49:35.792Z\n"

if let dateFromString = dateString.dateFromISO8601 {
    print(dateFromString)   // "2016-08-19 04:49:35 +0000\n"
    print(dateFromString.iso8601)  // "2016-08-19T04:49:35.792Z\n"
}

Since Voce has its date in Nsdate Voce format it should use Nsdateformatter to format the date for the user. You should not specify the format but the style of the date dateStyle (short, medium, long or full). This way the date will be formatted according to the user’s region preferences. Follow the link from reply from the site in England:

https://stackoverflow.com/a/28347285/2303865

If you need a table for reference:

inserir a descrição da imagem aqui

1

You can use the class Nsdateformatter to make this conversion.

Example:

let dateString = "2016-08-14T20:38:27.031-03:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZZZZZ"
let date = dateFormatter.dateFromString(dateString)
dateFormatter.dateFormat = "dd/MM/yyyy"
print(dateFormatter.stringFromDate(date!)) // Saída: 14/08/2016

1

Simply put, you must do just that:

let dateString = "2016-09-16T21:09:22.031-03:00" // Data de entrada
let dateFormatter = NSDateFormatter() //Instância do date Formatter
//Aqui você DEVE indicar qual formato é sua data de entrada. 
//Se caso não for do formato que você colocou, ocorrerá uma exception!
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZZZZZ" 
//Aqui você está Convertendo sua date String para uma data válida
let date = dateFormatter.dateFromString(dateString)
//Aqui você está mudando o formato que você quer retornar
dateFormatter.dateFormat = "dd/MM/yyyy"
//Aqui você está convertendo a data que você transformou para date em String no formato "novo" que você modificou acima.
print(dateFormatter.stringFromDate(date!)) // Saída: 16/09/2016

Browser other questions tagged

You are not signed in. Login or sign up in order to post.