-2

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

G5W
  • 36,531
  • 10
  • 47
  • 80
John
  • 183
  • 1
  • 3
  • 11
  • What do you mean "convert to timestamp"? Can you show what output you want and what you have so far? – Paulw11 Jun 03 '16 at 06:55
  • @Paulw11 I've edited my question and added this: 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 many time passed since that time(how many days, hours, minutes, seconds) – John Jun 03 '16 at 06:58
  • Take a look at NSDateFormatter, it allows you to convert NSDate to/from string formats. Once you have an NSDate, you seem to be looking for https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/instp/NSDate/timeIntervalSince1970 – David Berry Jun 03 '16 at 07:07
  • What is `1464370423`? – Paulw11 Jun 03 '16 at 07:19
  • @Paulw11 timestamp – John Jun 03 '16 at 07:19
  • @Paulw11 I just converted my date to timestamp. I do not get your question. Maybe you can help me to calculate those time distance in another way? – John Jun 03 '16 at 07:26
  • Oh ok. It is a `timeIntervalSince1970` – Paulw11 Jun 03 '16 at 07:27

5 Answers5

2

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
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

given the input string you can convert it to a date and subsequently to an NSTimeInterval since the current time using the following.

let inputDate = "2016-05-27 17:33:43+0400"

let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZZ"

if let aDate = dateFormatter.dateFromString(inputDate) {

    let timeInterval = aDate.timeIntervalSinceNow

    let dateComponentsFormatter = NSDateComponentsFormatter()

    if let dateString = dateComponentsFormatter.stringFromTimeInterval(abs(timeInterval)) {

        print ("Elapsed time=\(dateString)")
    }
}

Output:

Elapsed time=6d 17:51:52

You can get the date as the timestamp in your question using aDate.timeIntervalSince1970

Paulw11
  • 108,386
  • 14
  • 159
  • 186
0

I suggest that this could help you: How to get the current time as datetime

You can get the current time and calculate the difference using the server time and your current time.

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

Hope it helps.

Community
  • 1
  • 1
FabianLinn
  • 57
  • 8
0

This will tell you

"how many time"

passed since an event.

let date = Date()
let howManyTimePassed = date.timeIntervalSinceNow

TimeInterval is a typealias for a double, meaning its another way to say double. The value of the timeInterval represents seconds.

ScottyBlades
  • 12,189
  • 5
  • 77
  • 85
0

Try this class in Swift 5.1:

open class MyDateClass: NSObject {

    private var result:MyDateTime!
    
     init(dateStr: String, inputFormat: String) {
        let formatter = DateFormatter()
        formatter.dateFormat = inputFormat //"yyyy-MM-dd HH:mm:ss"
        formatter.calendar = Calendar(identifier: .gregorian)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        if let date = formatter.date(from: dateStr) {
            let dateComponentsFormatter = DateComponentsFormatter()
            dateComponentsFormatter.allowedUnits = [.year,.month,.day,.hour,.minute,.second]
            dateComponentsFormatter.unitsStyle = .full
            let strFromat = dateComponentsFormatter.string(from: date, to: Date()) ?? ""
            var trimmedString = strFromat.replacingOccurrences(of: " ", with: "")
            trimmedString = trimmedString.replacingOccurrences(of: "years", with: "")
            trimmedString = trimmedString.replacingOccurrences(of: "months", with: "")
            trimmedString = trimmedString.replacingOccurrences(of: "days", with: "")
            trimmedString = trimmedString.replacingOccurrences(of: "hours", with: "")
            trimmedString = trimmedString.replacingOccurrences(of: "minutes", with: "")
            trimmedString = trimmedString.replacingOccurrences(of: "seconds", with: "")
            let arr = trimmedString.split(separator: ",")
            let result = MyDateTime(year: Int(arr[0]), month: Int(arr[1]), day: Int(arr[2]), hour: Int(arr[3]), minute: Int(arr[4]), second: Int(arr[5]))
            self.result = result
        }
    }
    
    func getDateTime() -> MyDateTime {
        return result
    }
      
}

public struct MyDateTime {
    var year:Int?
    var month:Int?
    var day:Int?
    var hour:Int?
    var minute:Int?
    var second:Int?
}

And this class works like this:

let myClass = MyDateClass(dateStr: "2016-05-27 17:33:43", inputFormat: "yyyy-MM-dd HH:mm:ss")
let time = myClass.getDateTime()

Now you can show time as you wish.

reza_khalafi
  • 6,230
  • 7
  • 56
  • 82