gpt4 book ai didi

ios - 将时间戳转换为 NSDate

转载 作者:行者123 更新时间:2023-11-28 16:05:39 25 4
gpt4 key购买 nike

我有一个来自 JSON 的 double 值时间戳 1477933200000.0,我想先转换为 NSDate,然后再转换为 string。这就是我所做的,

let dateNow = NSDate(timeIntervalSinceNow: timestampDouble)
let date1970 = NSDate(timeIntervalSince1970: timestampDouble)
let dateRef = NSDate(timeIntervalSinceReferenceDate: timestampDouble)

let dateFormatter = NSDateFormatter()
// dateFormatter.dateFormat = "MM/dd/YYYY HH:MM:ss a"
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle

let convDateNow = dateFormatter.stringFromDate(dateNow)
print("Date Now: \(convDateNow)")

let convDate1970 = dateFormatter.stringFromDate(date1970)
print("Date Now: \(convDate1970)")

let convRefDate = dateFormatter.stringFromDate(dateRef)
print("Date Now: \(convRefDate)")

我试图在 http://www.epochconverter.com 中转换它它向我显示了正确的日期。但是这三种类型(timeIntervalSinceNowtimeIntervalSince1970timeIntervalSinceReferenceDate)都很奇怪。这是分别来自那些类型的结果。

Date Now: September 2, 48850 at 5:50:04 PM
Date Now: November 3, 48803 at 3:00:00 PM
Date Now: November 3, 48834 at 3:00:00 PM

那么我这里做错了什么?我只想了解现在的日期和 json(时间戳)中的日期之间的差异。

任何帮助将不胜感激。谢谢!

最佳答案

请注意,当您使用 epochconverter.com 时,会显示一条消息“假设此时间戳以毫秒”为单位。

现在,尝试删除尾随的三个零(小数点左侧)。它现在会假定您正在处理秒数,并且会为您提供相同的日期和时间。

在 iOS 中,NSTimeInterval(或 Swift 中的 TimeInterval)确实被定义为 double(或 Double),但它被解释为秒(具有亚毫秒精度)。因此,各种 NSDate() 构造函数重载都期望参数以秒为单位表示。

因此您可能需要将该时间戳除以 1000 才能将毫秒转换为秒。

关于ios - 将时间戳转换为 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40336012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com