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

vs91vp4v  于 2022-11-06  发布在  Swift
关注(0)|答案(5)|浏览(222)

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

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

现在,我想检测一下,从那个日期算起,过去了多少时间?例如1 day 5 hours 10 minutes 20 seconds
我知道如何从时间戳计算这个,但不知道如何将它转换为时间戳。
有人能帮我吗?

例如:

将此2016-05-27 17:33:43+0400转换为此1464370423
也许还有别的解决办法,我只是想计算一下,从那以后过了多少时间

sqyvllje

sqyvllje1#

我建议这可以帮助你: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

希望能有所帮助。

wpx232ag

wpx232ag2#

这会告诉你
“多少次”
自事件以来已过去。

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

TimeIntervaldoubletypealias,意思是double的另一种说法。timeInterval的值表示秒。

cmssoen2

cmssoen23#

请在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?
}

这个类的工作原理如下:

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

现在您可以随意显示时间。

jtw3ybtb

jtw3ybtb4#

您可以使用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
}
at0kjp5o

at0kjp5o5#

给定输入字符串,您可以使用以下代码将其转换为日期,然后转换为自当前时间以来的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)")
    }
}

输出量:
经过时间= 6天17:51:52
您可以使用aDate.timeIntervalSince1970在问题中获取日期作为时间戳

相关问题