首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Swift中的日期到毫秒和返回日期

Swift中的日期到毫秒和返回日期
EN

Stack Overflow用户
提问于 2016-10-19 14:29:29
回答 10查看 145K关注 0票数 86

我正在取当前的时间,以UTC为单位,并以纳秒为单位,然后我需要拿出纳秒,然后在当地时间返回一个日期。

我可以得到时间纳秒,然后回到一个日期字符串,但时间是复杂的,当我从一个字符串到日期。

代码语言:javascript
运行
复制
//Date to milliseconds
func currentTimeInMiliseconds() -> Int! {
    let currentDate = NSDate()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: dateFormatter.string(from: currentDate as Date))
    let nowDouble = date!.timeIntervalSince1970
    return Int(nowDouble*1000)
}

//Milliseconds to date
extension Int {
    func dateFromMilliseconds(format:String) -> Date {
        let date : NSDate! = NSDate(timeIntervalSince1970:Double(self) / 1000.0)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        dateFormatter.timeZone = TimeZone.current
        let timeStamp = dateFormatter.string(from: date as Date)
    
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return ( formatter.date( from: timeStamp ) )!
    }
}

时间戳是正确的,但返回的日期不是。

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2016-10-19 15:04:51

我不明白你为什么要用绳子.

代码语言:javascript
运行
复制
extension Date {
    var millisecondsSince1970:Int64 {
        Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }
    
    init(milliseconds:Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}


Date().millisecondsSince1970 // 1476889390939
Date(milliseconds: 0) // "Dec 31, 1969, 4:00 PM" (PDT variant of 1970 UTC)
票数 248
EN

Stack Overflow用户

发布于 2017-09-19 07:52:53

As @Travis解决方案有效,但在某些情况下

var millisecondsSince1970:Int 将导致应用程序崩溃,

有错误

双值不能转换为Int,因为如果发生Int.max,结果将大于,请使用Int64更新您的答案

这是最新的答案

代码语言:javascript
运行
复制
extension Date {
 var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
        //RESOLVED CRASH HERE
    }

    init(milliseconds:Int) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
    }
}

关于国际定义。

在32位平台上,Int的大小与Int32相同,而在64位平台上,Int的大小与Int64相同.

通常,我在iPhone 5中遇到这个问题,它在32位env中运行.新设备现在运行64位env。他们的Int将是Int64

希望这对同样有问题的人有帮助。

票数 55
EN

Stack Overflow用户

发布于 2018-03-30 09:19:37

@Travis解决方案是正确的,但是当生成日期时它会损失毫秒。我在日期中添加了一行,以包括毫秒:

如果您不需要这种精度,请使用Travis解决方案,因为它会更快。

代码语言:javascript
运行
复制
extension Date {

    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }

    init(millis: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
        self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
    }

}
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40134323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档