[swift] Convert string to date in Swift

How can I convert this string "2016-04-14T10:44:00+0000" into an NSDate and keep only the year, month, day, hour?

The T in the middle of it really throws off what I am used to when working with dates.

This question is related to swift nsdate nsdateformatter

The answer is


In Swift 4.1 you can do:

func getDate() -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.locale = Locale.current
    return dateFormatter.date(from: "2015-04-01T11:42:00") // replace Date String
}

Just your passing your dateformate and your date then you get Year,month,day,hour. Extra info

func GetOnlyDateMonthYearFromFullDate(currentDateFormate:NSString , conVertFormate:NSString , convertDate:NSString ) -> NSString
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = currentDateFormate as String
        let formatter = NSDateFormatter()
        formatter.dateFormat = Key_DATE_FORMATE as String
        let finalDate = formatter.dateFromString(convertDate as String)
        formatter.dateFormat = conVertFormate as String
        let dateString = formatter.stringFromDate(finalDate!)

        return dateString
    }


Get Year

let Year = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "YYYY", convertDate: "2016-04-14T10:44:00+0000") as String


Get Month

let month = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "MM", convertDate: "2016-04-14T10:44:00+0000") as String


Get Day

let day = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "dd", convertDate: "2016-04-14T10:44:00+0000") as String


Get Hour

let hour  = self.GetOnlyDateMonthYearFromFullDate("yyyy-MM-dd'T'HH:mm:ssZ", conVertFormate: "hh", convertDate: "2016-04-14T10:44:00+0000") as String

just Step 1 > get the String value from JSON or dataSource

Step 2 > create a local variable and assign it.

let startDate = CurrentDashBoard.startdate

Step 3> create an instance of DateFormatter.

let dateFormatter = DateFormatter()

step 4> call the dateFormat from dateFormatter and provide saved date dataType.

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"("may be String formate")

step 5> Assign the Local variable to this variable to convert.

let dateFromStringstartDate : NSDate = dateFormatter.date(from: startDate)! as NSDate

Step 6> provide your required date Formate by the following code.

dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"

Step 6> Assign it to label/text

cell.lblStartDate.text = String(format: "%@", strstartDate)

Code:

let startDate = CurrentDashBoard.startdate let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss" let dateFromStringstartDate : 
NSDate = dateFormatter.date(from: startDate)! as NSDate
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let strstartDate = dateFormatter.string(from: dateFromStringstartDate as Date)

Swift 3.0 - 4.2

import Foundation

extension String {

    func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{

        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from: self)

        return date

    }
}

extension Date {

    func toString(withFormat format: String = "EEEE ? d MMMM yyyy") -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.calendar = Calendar(identifier: .persian)
        dateFormatter.dateFormat = format
        let str = dateFormatter.string(from: self)

        return str
    }
}

Please use an ISO8601 parsing library for doing this. There are too many ways how the string could be encoded. Don't rely on a specific format and don't rely on the server sending always the same. The problems start with the 'Z' at the end and it will extend through all varieties of the standard. A parsing library will handle all cases and will always provide a safe conversion - whereas a fixed formatting string is likely to fail in the future.

You could use one of these libraries. They are also available on CococaPods:

https://github.com/boredzo/iso-8601-date-formatter/

https://github.com/malcommac/SwiftDate

Take a look at the implementations. They are both several hundred lines long - for good reason.

With regards to the question: You can pull out the date components from the date using NSDateComponents. The example on the website covers exactly your case.

https://developer.apple.com/documentation/foundation/nscalendar/1414841-components?language=objc

Please be aware, that converting your date will take into account the time zone. You might want to set the 'locale' of the NSCalendar explicitly.


make global function

func convertDateFormat(inputDate: String) -> String {

     let olDateFormatter = DateFormatter()
     olDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

     let oldDate = olDateFormatter.date(from: inputDate)

     let convertDateFormatter = DateFormatter()
     convertDateFormatter.dateFormat = "MMM dd yyyy h:mm a"

     return convertDateFormatter.string(from: oldDate!)
}

Called function and pass value in it

get_OutputStr = convertDateFormat(inputDate: "2019-03-30T05:30:00+0000")

and here is output

Feb 25 2020 4:51 PM



 

Sometimes, converting string to Date in swift can result to return nil so that you should add "!" mark to format.date function!

let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"

let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!

Swift 5. To see IF A DATE HAS PASSED:

let expiryDate = "2020-01-10" // Jan 10 2020

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

if Date() < dateFormatter.date(from: expiryDate) ?? Date() {
    print("Not Yet expiryDate")
} else {
    print("expiryDate has passed")
}

Hi You have separate T Format and then convert as you like

// create dateFormatter with UTC time format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-04-01T11:42:00")

// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
let timeStamp = dateFormatter.stringFromDate(date!)

In swift4,

    var Msg_Date_ = "2019-03-30T05:30:00+0000"

    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "MMM dd yyyy h:mm a"  //"MMM d, h:mm a" for  Sep 12, 2:11 PM
    let datee = dateFormatterGet.date(from: Msg_Date_)
    Msg_Date_ =  dateFormatterPrint.string(from: datee ?? Date())

    print(Msg_Date_)

//output :- Mar 30 2019 05:30 PM


Try the following date Format.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter. dateFromString (strDate)

Hope it helps..

Swift 4.1 :

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

Just use SwifterSwift.

stringDate = "2020-04-26T08:56:17.987Z"
let date = Date(iso8601String: stringDate)

I was getting crazy with this format as well.

See the solution below.

Your String that came from your back or another source:

    let isoDate = "2020-05-06 20:00:00-03"

Identify the date format

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!

Now that you have the date as Date() you can change to whatever format you want using the formatDate.string

    let formatDate = DateFormatter()
    formatDate.dateFormat = "dd/MM/yyyy HH:mm"
    let drawDate = formatDate.string(from: date)
    print(drawDate)

Output:

    06/05/2020 20:00

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to nsdate

Get current date in Swift 3? How to get time (hour, minute, second) in Swift 3 using NSDate? Convert string to date in Swift Date Format in Swift How to convert string to date to string in Swift iOS? Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift Get day of week using NSDate Get UTC time and local time from NSDate object How can I convert string date to NSDate? How do you create a Swift Date object?

Examples related to nsdateformatter

Convert NSDate to String in iOS Swift Convert string to date in Swift Date Format in Swift How to convert string to date to string in Swift iOS? Xcode swift am/pm time to 24 hour format Swift - iOS - Dates and times in different format Get current NSDate in timestamp format Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds