简体   繁体   English

将NSDate转换为Integer,Swift 3

[英]Convert NSDate to Integer, Swift 3

So my goal is to convert the time from an NSDate to an integer however, I am unsure of how to go about this. 所以我的目标是将时间从NSDate转换为整数,但是,我不确定该如何处理。 I have tried doing a simple conversion such as Int(...) however it does not work. 我尝试做一个简单的转换,例如Int(...),但是它不起作用。 Is this due to the fact that the string includes AM or PM? 这是由于字符串包含AM还是PM? I would really appreciate any help towards trying to get the time to be an integer. 我非常感谢您尝试将时间设为整数。 Thank you. 谢谢。

var firstDate = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: DateFormatter.Style.none, timeStyle: DateFormatter.Style.short)

This is generated in the view did load section. 这是在“视图加载”部分中生成的。 Again any help would be very much appreciated, thank you. 再次感谢您的任何帮助。

EDIT: 编辑:

Sorry reading over the question it probably was not particularly clear as to what I'm after. 抱歉阅读了这个问题,关于我所追求的可能还不是很清楚。 I want to be able to find the difference in time between two different NSDates. 我希望能够找到两个不同的NSDate之间的时间差异。 This will further be used as a countdown feature. 这将进一步用作倒计时功能。 The problem associated with this is that I am unsure of exactly how I am going to subtract two strings. 与此相关的问题是我不确定我将如何减去两个字符串。 Therefore I figured that if I can change the hours, minutes and seconds to integers, I could then subtract them. 因此,我认为如果可以将小时,分钟和秒更改为整数,则可以将它们相减。 What I need assistance with is any way which I can achieve this. 我需要帮助的是可以实现此目标的任何方法。 Perhaps changing the values to intervals is a bad way of doing this but it was just a thought I had and am open to any suggestions. 也许将值更改为时间间隔是执行此操作的不好方法,但这只是我的想法,可以接受任何建议。

It depends on what is the integer supposed to represent. 这取决于应该表示的整数。 Seconds can be obtained by getting time interval from another date. 可以通过获取另一个日期的时间间隔来获得秒数。 For example: 例如:

let date1 = Date()
let date2 = Date.init(timeInterval: 12345, since: date1)

let timeInterval = Int(date2.timeIntervalSince(date1))
// timeInterval = 12345 and is an int, the unit is seconds

So, you don't subtract strings, but work with Date or NSDate directly... 因此,您无需减去字符串,而是直接使用Date或NSDate ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM