Convert String to NSDate with Swift 2

后端 未结 2 1074
慢半拍i
慢半拍i 2021-01-01 19:18

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 dat         


        
相关标签:
2条回答
  • 2021-01-01 19:40

    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!
        }
    
    0 讨论(0)
  • 2021-01-01 19:55

    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.

    0 讨论(0)
提交回复
热议问题