Search code examples
iosswiftswift2nsdate

How to calculate how much time passed from the date with timezone?


I get from the server a date with this format:

2016-05-27 17:33:43+0400

Now, I want to detect, how much time passed since that date? For example 1 day 5 hours 10 minutes 20 seconds.

How can I do it? I know how to calculate this from the timestamp, but do not know how to convert this to a timestamp.

Can anyone help me with it?

For example:

Convert this 2016-05-27 17:33:43+0400 to 1464370423 this

Or maybe there are another solution. I just want to calculate how much time passed since that time


Solution

  • You can use NSDateComponents formatter to get the relative time between two dates. Regarding the date string format you need to use xx for the time zone part.

    let dateStr = "2016-05-27 17:33:43+0400"
    
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ssxx"
    formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
    formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    if let date = formatter.dateFromString(dateStr) {
        print(date)   // "2016-05-27 13:33:00 +0000\n" -4hs
        let dateComponentsFormatter = NSDateComponentsFormatter()
        dateComponentsFormatter.allowedUnits = [.Day,.Hour,.Minute,.Second]
        dateComponentsFormatter.unitsStyle = .Full
        print(dateComponentsFormatter.stringFromDate(date, toDate: NSDate()) ?? "") // 6 days, 17 hours, 51 minutes, 29 seconds
    }