将带有纪元时间和时区的时间戳字符串转换为 NSDate

Convert timestamp string with epochal time and timezone into NSDate(将带有纪元时间和时区的时间戳字符串转换为 NSDate)
本文介绍了将带有纪元时间和时区的时间戳字符串转换为 NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个以下格式的字符串

I have a String in following format

"/Date(573465600000-0800)/"

如何将其转换为常规 NSDate 对象?

How do I convert this to regular NSDate object?

推荐答案

第一部分573465600000"是Unix纪元以来的时间以毫秒为单位,第二部分-0800"是时区规范.

The first part "573465600000" is the time since the Unix epoch in milliseconds, and the second part "-0800" is a time zone specification.

这里是将JSON(日期)解析为Swift的小改动这也涵盖了时区部分:

Here is a slight modification of Parsing JSON (date) to Swift which also covers the time zone part:

extension NSDate {
    convenience init?(jsonDate: String) {
        let prefix = "/Date("
        let suffix = ")/"
        let scanner = NSScanner(string: jsonDate)

        // Check prefix:
        if scanner.scanString(prefix, intoString: nil) {

            // Read milliseconds part:
            var milliseconds : Int64 = 0
            if scanner.scanLongLong(&milliseconds) {
                // Milliseconds to seconds:
                var timeStamp = NSTimeInterval(milliseconds)/1000.0

                // Read optional timezone part:
                var timeZoneOffset : Int = 0
                if scanner.scanInteger(&timeZoneOffset) {
                    let hours = timeZoneOffset / 100
                    let minutes = timeZoneOffset % 100
                    // Adjust timestamp according to timezone:
                    timeStamp += NSTimeInterval(3600 * hours + 60 * minutes)
                }

                // Check suffix:
                if scanner.scanString(suffix, intoString: nil) {
                    // Success! Create NSDate and return.
                    self.init(timeIntervalSince1970: timeStamp)
                    return
                }
            }
        }

        // Wrong format, return nil. (The compiler requires us to
        // do an initialization first.)
        self.init(timeIntervalSince1970: 0)
        return nil
    }
}

例子:

if let theDate = NSDate(jsonDate: "/Date(573465600000-0800)/") {
    println(theDate)
} else {
    println("wrong format")
}

输出:

1988-03-04 00:00:00 +0000

<小时>

Swift 3 (Xcode 8) 更新:

extension Date {
    init?(jsonDate: String) {
        let prefix = "/Date("
        let suffix = ")/"
        let scanner = Scanner(string: jsonDate)

        // Check prefix:
        guard scanner.scanString(prefix, into: nil)  else { return nil }

        // Read milliseconds part:
        var milliseconds : Int64 = 0
        guard scanner.scanInt64(&milliseconds) else { return nil }
        // Milliseconds to seconds:
        var timeStamp = TimeInterval(milliseconds)/1000.0

        // Read optional timezone part:
        var timeZoneOffset : Int = 0
        if scanner.scanInt(&timeZoneOffset) {
            let hours = timeZoneOffset / 100
            let minutes = timeZoneOffset % 100
            // Adjust timestamp according to timezone:
            timeStamp += TimeInterval(3600 * hours + 60 * minutes)
        }

        // Check suffix:
        guard scanner.scanString(suffix, into: nil) else { return nil }

        // Success! Create NSDate and return.
        self.init(timeIntervalSince1970: timeStamp)
    }
}

例子:

if let theDate = Date(jsonDate: "/Date(573465600000-0800)/") {
    print(theDate)
} else {
    print("wrong format")
}

这篇关于将带有纪元时间和时区的时间戳字符串转换为 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Can`t copy file from bundle to documents directory in iOS(无法将文件从捆绑包复制到 iOS 中的文档目录)
How to copy a quot;Dictionaryquot; in Swift?(如何复制“字典在斯威夫特?)
Swift - How to mutate a struct object when iterating over it(Swift - 迭代结构对象时如何对其进行变异)
How to copy text to clipboard/pasteboard with Swift(如何使用 Swift 将文本复制到剪贴板/粘贴板)
Swift Cannot invoke #39;find#39; with an argument list of type #39;([Score], Score)#39; where Score is a struct(Swift 无法使用类型为“([Score],Score)的参数列表调用“find,其中 Score 是一个结构)
How to load image asynchronously with Swift using UIImageViewExtension and preventing duplicate images or wrong Images loaded to cells(如何使用 UIImageViewExtension 与 Swift 异步加载图像并防止重复图像或错误图像加载到单元格) - IT屋-程序员软