简体   繁体   中英

Converting Date to “/Date(631148400000+0100)/” string in Swift

I need to convert Swift Date object to date ticks string like "/Date(631148400000+0100)/".

The following link tells me how to convert date ticks string to Date object but not the vice-versa: How to convert date like \\/Date(1440156888750-0700)\\/ to something that Swift can handle?

How can I do that? Thanks in advance.

From Stand-Alone JSON Serialization :

DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.

And from Use JSON.NET to parse json date of format Date(epochTime-offset)

... In this screwy format , the timestamp portion is still based solely on UTC. The offset is extra information. It doesn't change the timestamp. You can give a different offset, or omit it entirely and it's still the same moment in time.

So the number of ticks is the number of milliseconds since Januar 1, 1970 GMT. Adding a time zone specification would only change how the date is presented locally in .NET, and one can simply omit that part when generating a JSON date string:

extension Date {
    var jsonDate: String {
        let ticks = lround(timeIntervalSince1970 * 1000)
        return "/Date(\(ticks))/"
    }
}

Example:

print(Date().jsonDate) // /Date(1481446227993)/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM