How to convert a String to Date in Swift

0

I get the date as following 2016-08-14T20: 38: 27.031-03: 00 as string, I would like to move to date in the default dd / MM / yyyy, I already searched the net for some solutions but were not useful

    
asked by anonymous 16.08.2016 / 04:02

3 answers

3

For this date format 2016-08-14T20:38:27.031-03:00 iso8601, you need to use the following format with a thousandths of seconds SSS and XXX for time zone:

-03:00

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"
}

Once you have your date in NSDate format you should use the NSDateFormatter to format the date for the user. You should not specify the format but the date style Z (short, medium, long or full). This way the date will be formatted according to the user's region preferences. Follow the response link from the English site:

link

If you need a table for reference:

    
19.08.2016 / 01:08
1

You can use the NSDateFormatter class to do 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
    
16.08.2016 / 06:35
1

In a simplified way, you should 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
    
16.09.2016 / 16:56