在Swift中将日期转换为整数 [英] Convert Date to Integer in Swift

查看:125
本文介绍了在Swift中将日期转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在更新Swift 3的一些旧的Swift 2答案。我的回答 这个问题虽然不容易更新,因为该问题具体要求 NSDate 而不是日期。所以我正在创建一个新版本的问题,我可以更新我的答案。

I am updating some of my old Swift 2 answers to Swift 3. My answer to this question, though, is not easy to update since the question specifically asks for NSDate and not Date. So I am creating a new version of that question that I can update my answer for.

问题

如果我从日期开始这样的实例

let someDate = Date()

我将如何将其转换为整数?

how would I convert that to an integer?

相关但不同

这些问题正在要求不同的东西:

These questions are asking different things:

  • Swift convert unix time to date and time
  • Converting Date Components (Integer) to String
  • Convert Date String to Int Swift

推荐答案

这个答案使用Swi ft 3语法。对于具有 NSDate 的Swift 2,请参见此答案

This answer uses Swift 3 syntax. For Swift 2 with NSDate, see this answer.

// using current date and time as an example
let someDate = Date()

// convert Date to TimeInterval (typealias for Double)
let timeInterval = someDate.timeIntervalSince1970

// convert to Integer
let myInt = Int(timeInterval)

执行双重 Int 转换导致毫秒丢失。如果需要毫秒数乘以1000,然后转换为 Int

Doing the Double to Int conversion causes the milliseconds to be lost. If you need the milliseconds then multiply by 1000 before converting to Int.

包括相反的完整性。

// convert Int to Double
let timeInterval = Double(myInt)

// create NSDate from Double (NSTimeInterval)
let myNSDate = Date(timeIntervalSince1970: timeInterval)

我也可以使用 timeIntervalSinceReferenceDate 而不是 timeIntervalSince1970 只要我是一致的。这是假定时间间隔是秒。请注意,Java使用毫秒。

I could have also used timeIntervalSinceReferenceDate instead of timeIntervalSince1970 as long as I was consistent. This is assuming that the time interval is in seconds. Note that Java uses milliseconds.

这篇关于在Swift中将日期转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆