srivas srivas - 7 months ago 11
Swift Question

how to add Hours to date in swift in this format "2015-06-11T00:00:00.000Z" as in one string while parsing in SWIFT

How to add Hours to date in swift in this format "2015-06-11T00:00:00.000Z" as in one string while parsing in SWIFT.

I was trying to add time to date in ons string for parsing in SWIFT. I have two texfields representing date and time from the date picker, but when I parse the string only date displays. I want to combine date and time in string and send it to the server. Please help me in swift Language

Answer

You can do it using NSCalendar method dateBySettingHour as follow:

let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"

if let dateFromString = df.dateFromString("2015-06-11T00:00:00.000Z") {

    let hour = 4

    if let dateFromStringWithTime = NSCalendar.currentCalendar().dateBySettingHour(hour, minute: 0, second: 0, ofDate: dateFromString, options: nil) {

        let df = NSDateFormatter()
        df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
        let resultString = df.stringFromDate(dateFromStringWithTime)

        print(resultString) // "2015-06-11T04:00:00.000Z"
    }

}