iOSGeek
iOSGeek

Reputation: 5577

Convert String to NSDate with Swift 2

I'm trying to convert a string to NSDate here is my code

     let strDate = "2015-11-01T00:00:00Z" // "2015-10-06T15:42:34Z"
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
    print ( dateFormatter.dateFromString( strDate ) )

I keep getting nil as a result

Upvotes: 15

Views: 17258

Answers (2)

Bijender Singh Shekhawat
Bijender Singh Shekhawat

Reputation: 4474

For swift 4 and swift 3.2 updated answer.

here all Date related function mentioned.

hop these function useful for you.

1=> Timestamp to Date

func timeStampToDate(_timestamp : String, _dateFormat : String) -> String{

        var LOCAL_TIME_ZONE: Int { return TimeZone.current.secondsFromGMT() }

        var date = Date(timeIntervalSince1970: TimeInterval(_timestamp)!)
        date += TimeInterval(LOCAL_TIME_ZONE as NSNumber)
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
        dateFormatter.locale = NSLocale.current
        dateFormatter.dateFormat = _dateFormat //Specify your format that you want
        let strDate = dateFormatter.string(from: date)
        return strDate
    }

2=> Date to String

func DateToString(date : Date, dateFormatte : String) -> String {

        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = dateFormatte

        print("Dateobj: (dateFormatter.string(from: dateObj!))")

        return (dateFormatter.string(from: date as Date))

    }

3=> String to date

func StringDateToDate(dateString : String, dateFormatte : String) -> Date {

        //let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"

        //let dateFormatte = "EEE, dd MMM yyyy hh:mm:ss +zzzz"

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormatte
        let dateObj = dateFormatter.date(from: dateString)
        if dateObj == nil {
            return Date()
        }
        return dateObj!
    }

Upvotes: 0

zaph
zaph

Reputation: 112857

The "T" in the format string needs to be single quoted so it will not be consider a symbol:

Swift 3.0

let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:strDate)
print("date: \(date!)")

Output:

date: 2015-11-01 00:00:00 +0000

Swift 2.x

let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(strDate)
print("date: \(date!)")

Output:

date: 2015-11-01 00:00:00 +0000

See: Date Field SymbolTable.

This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.

Upvotes: 31

Related Questions