在Swift中将日期转换为整数

编程入门 行业动态 更新时间:2024-10-25 10:29:54
本文介绍了在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将unix时间转换为日期和时间
  • 将日期组件(整数)转换为字符串
  • 将日期字符串转换为Int Swift
  • 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中将日期转换为整数

本文发布于:2023-10-24 16:50:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524482.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   转换为   中将   日期   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!