将“当前时间”转换为“当前时间”至“自00:00起以分钟为单位的时间”计算帮助
我没有经常使用 NSDate,所以我需要一些帮助来完成我正在做的计算。
我有一个整数,其中包含自午夜以来我的商店的关闭时间(以分钟为单位)。基本上,我的商店在下午 5 点关门,这给了我整数 1020。
所以现在是晚上 10.45 或 22.45。从 00:00 开始的整数是 1365,由此我可以说
if (storeHour < currentTime) {
// closed!
}
但是,我不知道如何从 NSDate 获得的“22.45”将其转换为表示从 00:00 开始的时间的整数。 NSDate 中有什么可以帮助我的吗?
谢谢
I haven't used NSDate that much, so I'd like some help with a calculation I am doing.
I have an integer that has my store's closing hour in minutes since midnight. Basically, my store closes at 5.00PM, which gives me the integer 1020.
So right now it's 10.45PM or 22.45. Integer since 00:00 is 1365, and from this I can say
if (storeHour < currentTime) {
// closed!
}
However, I don't know how I get from "22.45" that I have from NSDate to converting it to an integer representing time since 00:00. Is there something in NSDate that can help me with that?
Thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我确实建议使用
NSDate
对象来存储商店关闭的时间,而不是使用您自己的自定义整数格式。不幸的是,NSDate
既代表日期又代表日期时间。无论如何,您可以检查
NSDateComponents
。您可以有一个实用程序方法,例如:I do recommend using an
NSDate
object to store the time the store closes instead of using your own custom integer format. It's unfortunate thatNSDate
represents both date and time of date.In any case, you can check
NSDateComponents
. You can have a utilities method like:斯威夫特5
例如,这为您提供了自午夜以来的当前分钟数
Swift 5
This for exemple gives you the current number of minutes since midnight
@notnoop 回复的快速版本:
A swift version of what @notnoop has replied:
如果您有另一个设置为午夜的
NSDate
,那么您可以使用NSDate对象的timeIntervalSinceDate
方法来获取NSTimeInterval
两者之间的区别。或者,如果您总是想将午夜与当前时间进行比较,您可以在午夜 NSDate 上调用timeIntervalSinceNow
方法,并且您会得到一个NSTimeInterval
返回(尽管负)与午夜和当前时间之间的差异。NSTimeInterval
由标准定义为double
,它保存秒数(以及任何小数秒)。If you have another
NSDate
which is set to midnight, then you can use thetimeIntervalSinceDate
method of the NSDate object to get anNSTimeInterval
back with the difference between the two. Alternatively, if you're always wanting to compare midnight with the current time, you could call thetimeIntervalSinceNow
method on the midnight NSDate and you'd get anNSTimeInterval
back (albeit negative) with the difference between midnight and the current time.NSTimeInterval
is defined as adouble
by the standard which holds a number of seconds (and any fractional seconds).这是一种现代方法,不需要任何额外的数学。
Objective-C
Swift 3+ 作为
Date
扩展用法:
This is a contemporary way without any extra math.
Objective-C
Swift 3+ as
Date
extensionUsage: