Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time comparisons in swift

Tags:

ios

swift

Question:

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.

Other Info:

I am currently using

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

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.

like image 504
Byron Coetsee Avatar asked Jun 19 '14 21:06

Byron Coetsee


People also ask

How do I get the difference between two times in Swift?

To calculate the time difference between two Date objects in seconds in Swift, use the Date. timeIntervalSinceReferenceDate method.

Is Date equatable Swift?

Swift's Date struct conforms to both Equatable and Comparable , which means you check two dates for equality and compare them to see which is earlier.

Is Swift same day?

Same day delivery is the heartbeat of Swift Delivery & Logistics. For nearly 30 years, we have provided same day, on-demand courier and freight delivery to homes and businesses 24 hours a day, 7 days a week. We also offer next day and prescheduled services. Learn more here.


1 Answers

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
}

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)
like image 171
Duyen-Hoa Avatar answered Oct 07 '22 01:10

Duyen-Hoa