Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

ios - Time comparisons in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...