如何计算从带时区的日期过去了多少时间?

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

我从服务器得到一个格式如下的日期:

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

现在,我想检测自该日期以来经过了多少时间?例如 1 day 5 hours 10 minutes 20 seconds.

我该怎么做?我知道如何从时间戳中计算出来,但不知道如何将其转换为时间戳。

有人可以帮我吗?

例如:

将此 2016-05-27 17:33:43+0400 转换为 1464370423

或者也许还有其他解决方案。我只想计算从那时起经过了多少时间

我建议这对你有帮助:How to get the current time as datetime

您可以获取当前时间,并计算服务器时间与您当前时间的时差。

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

希望对您有所帮助。

您可以使用 NSDateComponents 格式化程序来获取两个日期之间的相对时间。关于日期字符串格式,您需要对时区部分使用 xx

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
}

给定输入字符串,您可以将其转换为日期,然后使用以下命令将其转换为 NSTimeInterval 自当前时间以来。

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)")
    }
}

输出:

Elapsed time=6d 17:51:52

您可以使用 aDate.timeIntervalSince1970

获取问题中的日期作为时间戳

这会告诉你

"how many time"

自事件后已通过。

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

TimeIntervaltypealias 对应 double,意思是 double 的另一种说法。 timeInterval的值代表秒。

Swift 5.1:

中试试这个 class
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?
}

而这个 class 是这样工作的:

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

现在你可以随心所欲地显示时间了。