Skip to content

Instantly share code, notes, and snippets.

@BasThomas
Last active August 29, 2015 14:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save BasThomas/d6d3da1434a679ed9c43 to your computer and use it in GitHub Desktop.
Get the soonest date from a list of dates
extension NSDate
{
/**
Checks if the date is in the past.
:returns: If date is passed or not
*/
func inPast() -> Bool
{
let now = NSDate()
if self.laterDate(now) == now
{
return true
}
return false
}
}
/**
Returns the soonest date in a list of dates.
:param: dates One or more NSDate objects.
:returns: NSDate, which is the closest to now.
*/
func soonestDate(dates: NSDate...) -> NSDate
{
var soonest: NSDate!
for date in dates
{
if soonest != nil
{
soonest = date.earlierDate(soonest)
}
else
{
soonest = date
}
}
return soonest
}
/**
Returns the soonest date(s) in a list of dates.
:param: dates One or more NSDate objects.
:returns: NSDate(s), which is/are the closest to now.
*/
func soonestDates(dates: NSDate...) -> [NSDate]?
{
var soonest: [NSDate]!
for date in dates
{
if date.inPast()
{
continue
}
if soonest != nil
{
if (soonest.first!.isEqualToDate(date))
{
soonest.append(date)
}
else if (soonest.first!.earlierDate(date) == date)
{
soonest = [date]
}
}
else if (!dates.first!.inPast())
{
soonest = [date]
}
}
return soonest
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment