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.
To calculate the time difference between two Date objects in seconds in Swift, use the Date. timeIntervalSinceReferenceDate method.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With