时间比较迅速 [英] Time comparisons in swift

查看:187
本文介绍了时间比较迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我需要比较2次 - 当前时间和第1次。如果设定的时间是将来,请查看剩余的时间,直到所述未来时间。

I need to compare 2 times - the current time and a set one. If the set time is in the future, find out how many minutes remain until said future time.

其他信息:

我目前正在使用

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

我从SO的另一个答案中偷走了如何以Int格式获取当前时间。然后我将未来时间分成小时(Int)和分钟(Int)并比较那些......但是当你超过小时障碍时,这会变得很奇怪。

which I stole from another answer on SO about how to get the current time in Int format. I then split the future time into hour (Int) and minutes(Int) and compare those... But that gets odd when you go over the hour barrier.

推荐答案

你有比较功能来比较2 NSDate以知道哪一个更新。它返回NSCompareResults

You have compare function to compare 2 NSDate to know which one is more recent. It returns NSCompareResults

enum NSComparisonResult : Int {
    case OrderedAscending
    case OrderedSame
    case OrderedDescending
}

从2 NSDate获得距离(以秒为单位),你有.timeIntervalSinceDate() 。然后,你知道如何转换为分钟,小时,......

Get distance (in seconds) from 2 NSDate, you have .timeIntervalSinceDate(). Then, you know how to convert to minutes, hours, ...

let date1 : NSDate = ... 
let date2 : NSDate = ...

let compareResult = date1.compare(date2)

let interval = date1.timeIntervalSinceDate(date2)

这篇关于时间比较迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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