ios – Convert string to DATE type in swift 3

ios – Convert string to DATE type in swift 3

You can convert String Date into Date/NSDate like below code: –

Swift 3.2 & Swift 4.2

String to Date

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dd-MM-yyyy //Your date format
dateFormatter.timeZone = TimeZone(abbreviation: GMT+0:00) //Current time zone
//according to date format your date string
guard let date = dateFormatter.date(from: 01-01-2017) else {
    fatalError()
}
print(date) //Convert String to Date

Date to String

dateFormatter.dateFormat = MMM d, yyyy //Your New Date format as per requirement change it own
let newDate = dateFormatter.string(from: date) //pass Date here
print(newDate) //New formatted Date string

Output: –

2017-01-11 00:07:00 +0000
Jan 11, 2017

Output

Swift 4 ISO

let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: en_US_POSIX)
    dateFormatter.timeZone = TimeZone.autoupdatingCurrent
    dateFormatter.dateFormat = yyyy-MM-ddTHH:mm:ss.SSSZ

ios – Convert string to DATE type in swift 3

 func getDateFromString(dateStr: String) -> (date: Date?,conversion: Bool)
{
    let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
    let dateComponentArray = dateStr.components(separatedBy: /)

    if dateComponentArray.count == 3 {
        var components = DateComponents()
        components.year = Int(dateComponentArray[2])
        components.month = Int(dateComponentArray[1])
        components.day = Int(dateComponentArray[0])
        components.timeZone = TimeZone(abbreviation: GMT+0:00)
        guard let date = calendar.date(from: components) else {
            return (nil , false)
        }

        return (date,true)
    } else {
        return (nil,false)
    }

}

//Input: 23/02/2017

//Output: (2017-02-23 18:30:00 +0000, true)

Leave a Reply

Your email address will not be published. Required fields are marked *