【发布时间】:2019-03-29 12:51:22
【问题描述】:
我有一个来自 Json 的时间组件。我正在尝试根据发布时间对对象进行分组。
我有一个像1540432146 这样的时间间隔,它是一个双倍。
我正在使用将其转换为日期类型
guard let timeInMilliseconds = lastUpdateOn as? Double else {return NSDate()}
let timeInSeconds = timeInMilliseconds / 100000
print(timeInSeconds)
// get the Date
let dateTime = NSDate(timeIntervalSince1970: timeInSeconds)
因此我得到2018-10-25 10:54:20.325076+0900 作为输出。
是否可以删除其中的 Time 组件并再次将 Date 类型转换回 TimeIntervalSincel1970,因为稍后我将使用它对数组中的元素进行排序,比较 Double 会更容易
func getTime(lastUpdateOn:Any) -> NSDate{
guard let timeInMilliseconds = lastUpdateOn as? Double else {return NSDate()}
let timeInSeconds = timeInMilliseconds / 100000
// get the Date
let dateTime = NSDate(timeIntervalSince1970: timeInSeconds)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let datenew = dateFormatter.string(from: dateTime as Date)
let newDate = dateFormatter.date(from: datenew)
print(newDate)
return dateTime
}
这是我尝试过的函数,但它总是返回值(1970-06-27 15:00:00 +0000)。我做错了什么?
【问题讨论】:
-
一秒有 1000 毫秒,而不是 100000。
-
您先生是对的,我没有意识到,愚蠢的错误。谢谢你指出。它现在似乎工作正常。
-
你应该在 Swift 中使用
Date,而不是NSDate,你可以很容易地比较Dates。当你想显示日期时,你应该只转换回字符串