im attempting to only load posts that were created within 24 hours of the current time. Im having issues with the part where I set NSDate < NSDate, but being that NSDate is not an Int I don't know another way to accomplish the same task. Any help appreciated!
override func viewDidAppear(animated: Bool) {
var annotationQuery = PFQuery(className: "Post")
currentLoc = PFGeoPoint(location: MapViewLocationManager.location)
//annotationQuery.whereKey("Location", nearGeoPoint: currentLoc, withinMiles: 10)
annotationQuery.whereKeyExists("Location")
annotationQuery.findObjectsInBackgroundWithBlock {
(points, error) -> Void in
if error == nil {
// The find succeeded.
println("Successful query for annotations")
// Do something with the found objects
let myPosts = points as! [PFObject]
for post in myPosts {
let point = post["Location"] as! PFGeoPoint
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude)
annotation.title = post["title"] as! String!
let annotationSubTitleUser = post["username"] as! String!
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
formatter.timeStyle = .ShortStyle
let dateString = formatter.stringFromDate(post.createdAt!)
var current = NSDate()
var expireDate = NSDate(timeIntervalSinceNow: 60 * 60 * 24)
annotation.subtitle = "User: \(annotationSubTitleUser) Time: \(dateString)"
//Here is where I am having issues setting current < expireDate
if (current < expireDate) {
self.mapView.addAnnotation(annotation)
}
}
} else {
// Log details of the failure
println("Error: \(error)")
}
}
}
If we are trying to compare dates, NSDate has a compare method which accepts another NSDate argument and returns an NSComparisonResult.
if date1.compare(date2) == .OrderedDescending {
// date1 comes after date2
}
if date1.compare(date2) == .OrderedAscending {
// date1 comes before date2
}
if date1.compare(date2) == .OrderedSame {
// date1 and date2 are the same
}
Use:
if (current.timeIntervalSince1970() < expireDate.timeIntervalSince1970()) {
self.mapView.addAnnotation(annotation)
}
instead.
Use this code..
let interval = dateOne!.timeIntervalSinceDate(dateTwo!)
var numberOfDays = interval/(3600*24)
if (numberOfDays == 0) {
println("same day") //dateOne = dateTwo
}else if (numberOfDays>0){
println("two > one") //dateOne > dateTwo
}else if (numberOfDays<0){
println("two < one") //dateOne < dateTwo
}
This might helps you :)
In case you want to determine the earlier or the later between two dates, then the NSDate class can help you a lot towards this effort as it provides two methods named earlierDate and laterDate respectively. The syntax when using any of those methods is simple:
date1.earlierDate(date2)
And here’s how it works:
If the date1 object is earlier than date2, then the above method will return the value of the date1.
If the date2 object is earlier than date1, then the value of the date2 will be returned.
If the dates are equal, then the date1 is returned again.
All the above apply for the laterDate as well.
The second method of comparing two NSDate objects involves the use of the compare method of the NSDate class and the NSComparisonResult enum
// Comparing dates - Method #2
if date1.compare(date2) == NSComparisonResult.OrderedDescending {
print("Date1 is Later than Date2")
}
else if date1.compare(date2) == NSComparisonResult.OrderedAscending {
print("Date1 is Earlier than Date2")
}
else if date1.compare(date2) == NSComparisonResult.OrderedSame {
print("Same dates")
}
You can find out more from this Link.
Happy to help. :)
Related
How can I compare the values from data Base to my current date ? A date is saved in the data base when some action is performed, I need to compare that date with my current date and do some action. How can I do that ?
The date is saved my date base in this format:
var tasksin2 : Task?
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"
let mydate="\(dateFormatter.string(from: datePicker.date))"
tasksin2?.time=mydate
(UIApplication.shared.delegate as! AppDelegate).saveContext()
Here ya go:
extension String {
func toDate() -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy hh:mm"
return formatter.date(from: self)
}
}
class MyViewController: UIViewController {
var dateString1: String!
var dateString2: String!
override func viewDidLoad() {
super.viewDidLoad()
// set dateStrings
printDateTypes()
}
func printDateTypes() {
guard let date1 = dateString1.toDate() else {
print("dateString1: \(dateString1) | Failed to cast to \"dd/MM/yyyy hh:mm\"")
return
}
guard let date2 = dateString2.toDate() else {
print("dateString2: \(dateString2) | Failed to cast to \"dd/MM/yyyy hh:mm\"")
return
}
let isDescending = date1.compare(date2) == ComparisonResult.orderedDescending
print("orderedDescending: \(isDescending)")
let isAscending = date1.compare(date2) == ComparisonResult.orderedAscending
print("orderedAscending: \(isAscending)")
let isSame = date1.compare(date2) == ComparisonResult.orderedSame
print("orderedSame: \(isSame)")
}
}
I'm updating my app to Swift 3.0 syntax (I know it's still in beta but I want to be prepared as soon as it released).
Until the previous Beta of Xcode (Beta 5) I was able to compare two Date objects using the operands <, > and ==. But in the latest beta (Beta 6) this isn't working any more. Here are some screenshots:
As you can see in both screenshots, these are two Date objects. But I get the following error:
What am I doing wrong? The functions are still declared in the Date class:
static func >(Date, Date)
Returns true if the left hand Date is later in time than the right hand Date.
Is this just a Beta bug or am I doing something wrong?
I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.
let date1 = Date()
let date2 = Date().addingTimeInterval(100)
if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }
Date is Comparable & Equatable (as of Swift 3)
This answer complements #Ankit Thakur's answer.
Since Swift 3 the Date struct (based on the underlying NSDate class) adopts the Comparable and Equatable protocols.
Comparable requires that Date implement the operators: <, <=, >, >=.
Equatable requires that Date implement the == operator.
Equatable allows Date to use the default implementation of the != operator (which is the inverse of the Equatable == operator implementation).
The following sample code exercises these comparison operators and confirms which comparisons are true with print statements.
Comparison function
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
Sample Use
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2
from Swift 3 and above, Date is Comparable so we can directly compare dates like
let date1 = Date()
let date2 = Date().addingTimeInterval(50)
let isGreater = date1 > date2
print(isGreater)
let isSmaller = date1 < date2
print(isSmaller)
let isEqual = date1 == date2
print(isEqual)
Alternatively We can create extension on Date
extension Date {
func isEqualTo(_ date: Date) -> Bool {
return self == date
}
func isGreaterThan(_ date: Date) -> Bool {
return self > date
}
func isSmallerThan(_ date: Date) -> Bool {
return self < date
}
}
Use: let isEqual = date1.isEqualTo(date2)
Don't use comparators <, >, ==, !=.
Use compare(_ other: Date) function.
Usage
// Get current date
let dateA = Date()
// Get a later date (after a couple of milliseconds)
let dateB = Date()
// Compare them using switch
switch dateA.compare(dateB) {
case .orderedAscending : print("Date A is earlier than date B")
case .orderedDescending : print("Date A is later than date B")
case .orderedSame : print("The two dates are the same")
}
// Compare them using if
if dateA.compare(dateB) == .orderedAscending {
datePickerTo.date = datePicker.date
}
For me the problem was that I had my own extension to Date class that was defining all the compare operators. Now (since swift 3) that Date is comparable, these extensions are not needed. So I commented them out and it worked.
SWIFT 3: Don't know if this is what you're looking for. But I compare a string to a current timestamp to see if my string is older that now.
func checkTimeStamp(date: String!) -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier:"en_US_POSIX")
let datecomponents = dateFormatter.date(from: date)
let now = Date()
if (datecomponents! >= now) {
return true
} else {
return false
}
}
To use it:
if (checkTimeStamp(date:"2016-11-21 12:00:00") == false) {
// Do something
}
If you want to ignore seconds for example
you can use
func isDate(Date, equalTo: Date, toUnitGranularity: NSCalendar.Unit) -> Bool
Example compare if it's the same day:
Calendar.current.isDate(date1, equalTo: date2, toGranularity: .day)
To compare date only with year - month - day and without time for me worked like this:
let order = Calendar.current.compare(self.startDate, to: compareDate!, toGranularity: .day)
switch order {
case .orderedAscending:
print("\(gpsDate) is after \(self.startDate)")
case .orderedDescending:
print("\(gpsDate) is before \(self.startDate)")
default:
print("\(gpsDate) is the same as \(self.startDate)")
}
As of the time of this writing, Swift natively supports comparing Dates with all comparison operators (i.e. <, <=, ==, >=, and >). You can also compare optional Dates but are limited to <, ==, and >. If you need to compare two optional dates using <= or >=, i.e.
let date1: Date? = ...
let date2: Date? = ...
if date1 >= date2 { ... }
You can overload the <= and >=operators to support optionals:
func <= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs || lhs < rhs
}
func >= <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs || lhs > rhs
}
extension Date {
func isBetween(_ date1: Date, and date2: Date) -> Bool {
return (min(date1, date2) ... max(date1, date2)).contains(self)
}
}
let resultArray = dateArray.filter { $0.dateObj!.isBetween(startDate, and: endDate) }
Another way to do it:
switch date1.compare(date2) {
case .orderedAscending:
break
case .orderedDescending:
break;
case .orderedSame:
break
}
var strDateValidate = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let firstDate = dateFormatter.date(from:lblStartTime.text!)
let secondDate = dateFormatter.date(from:lblEndTime.text!)
if firstDate?.compare(secondDate!) == .orderedSame || firstDate?.compare(secondDate!) == .orderedAscending {
print("Both dates are same or first is less than scecond")
strDateValidate = "yes"
}
else
{
//second date is bigger than first
strDateValidate = "no"
}
if strDateValidate == "no"
{
alertView(message: "Start date and end date for a booking must be equal or Start date must be smaller than the end date", controller: self)
}
Swift 5:
1) If you use Date type:
let firstDate = Date()
let secondDate = Date()
print(firstDate > secondDate)
print(firstDate < secondDate)
print(firstDate == secondDate)
2) If you use String type:
let firstStringDate = "2019-05-22T09:56:00.1111111"
let secondStringDate = "2019-05-22T09:56:00.2222222"
print(firstStringDate > secondStringDate) // false
print(firstStringDate < secondStringDate) // true
print(firstStringDate == secondStringDate) // false
I'm not sure or the second option works at 100%. But how much would I not change the values of firstStringDate and secondStringDate the result was correct.
in Swift 3,4 you should use "Compare".
for example:
DateArray.sort { (($0)?.compare($1))! == .orderedDescending }
How do i configure a label and image according to a date range?
Let's say I have an image file name (Aquarius) and I want such that when the user picks a date in the date picker that falls between say January 21 to February 12, the image view displays the Aquarius image and the Label show the name of the image?
so far this is what I have but don't know how to go about it
#IBAction func birthDay(sender: AnyObject) {
let date = datePicker.date
}
Let's say you have date1 and date2 - your limit dates. And you have UIImageView named imageView.
#IBAction func birthDay( sender: AnyObject) {
let date = datePicker.date
if date1.compare(date) == date2.compare(date) { // date between date1 and date2
imageView.image = UIImage(named: "Aqurius")
} else {
imageView.image = nil // otherwise clear imageView
}
}
To simplify such task you can create extension for NSDate that contain all needed methods.
extension NSDate {
convenience init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let d = dateStringFormatter.dateFromString(dateString)!
self.init(timeInterval:0, sinceDate:d)
}
func isDateBetween(date1: NSDate, date2: NSDate) -> Bool {
return date1.compare(self) == date2.compare(self)
}
}
And now you can simplify datePicker's method to this:
#IBAction func birthDay( sender: AnyObject) {
let date = datePicker.date
if date.isDateBetween(NSDate("2015-06-05"), date2: NSDate("2015-07-05")) { // date between date1 and date2
imageView.image = UIImage(named: "Aqurius")
} else {
imageView.image = nil // otherwise clear imageView
}
}
UPDATE
Ok, if you want to choose from couple images you can try this:
let dates: [(NSDate, NSDate, String)] = [(NSDate("2015-06-05"), NSDate("2015-07-05"), "imgname1"), (NSDate("2015-08-05"), NSDate("2015-08-05"), "imgname2")] // and so on
let date = datePicker.date
for tuple in dates {
if date.isDateBetween(tuple.0, date2: tuple.1) {
let imageName = tuple.2
// do whatever you need
brea
}
}
+(NSString *)getStarString:(NSDate *)birth
{
if (![birth isKindOfClass:[NSDate class]]) {
return nil;
}
NSDateFormatter *df=[[NSDateFormatter alloc]init];
df.dateFormat=#"yyyy-MM-dd";
NSArray *arr=[[df stringFromDate:birth] componentsSeparatedByString:#"-"];
int m=[arr[1] intValue];
int d=[arr[2] intValue];
NSArray *astroArray=#[#"Capricorn",#"Aquarius",#"Pisces",#"Aries",#"Taurus",#"Gemini",#"Cancer",#"Leo",#"Virgo",#"Libra",#"Scorpio",#"Sagittarius",#"Capricorn"];
NSString *astroFormat = #"102123444543";
if (m<1||m>12||d<1||d>31){
return nil;
}
if(m==2 && d>29)
{
return nil;
}else if(m==4 || m==6 || m==9 || m==11) {
if (d>30) {
return nil;
}
}
NSInteger index=m-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19));
return astroArray[index];
}
I have a CoreData attributes that 2 (value, date). When I click on a UIButton, it added an entry corresponding to the value of the UIButton.
I will wish to limit the addition of entry to a daily. Basically, I will wish to check the current date and the date of the last entry. If it's value are identical, this is not added.
My Function
func data(sender: UIButton) {
// Date Format
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "YYYY/MM/dd"
let dateFormat = formatter.stringFromDate(date)
// Load Entity
let AppDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let theContext : NSManagedObjectContext = AppDel.managedObjectContext
let theEnt = NSEntityDescription.entityForName("Mood", inManagedObjectContext: theContext)
// Create Item
let newItem = Mood(entity: theEnt!, insertIntoManagedObjectContext: theContext)
newItem.mood = String(sender.tag)
newItem.date = dateFormat
// Save Item
do {
try theContext.save()
} catch _ {
}
}
Thank you in advance for your response.
If you fetch the Mood objects, sorted by date in descending order, the first item returned will be the last entry. You can set the fetchLimit to 1 to avoid loading more objects than are necessary. You can then test to see whether the date attribute matches, and handle accordingly:
func data(sender: UIButton) {
// Date Format
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "YYYY/MM/dd"
let dateFormat = formatter.stringFromDate(date)
// Get context and entity details
let AppDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let theContext : NSManagedObjectContext = AppDel.managedObjectContext
let theEnt = NSEntityDescription.entityForName("Mood", inManagedObjectContext: theContext)
// Fetch the latest entry
let fetch = NSFetchRequest()
fetch.entity = theEnt!
let sort = NSSortDescriptor(key: "date", ascending:false)
fetch.sortDescriptors = [sort]
fetch.fetchLimit = 1
let results = try! theContext.executeFetchRequest(fetch) as! [Mood]
// NB should do proper try/catch error checking
// Check for existing entry
if (results.count > 0) {
// Check whether date matches
if (results[0].date != dateFormat) {
let newItem = Mood(entity: theEnt!, insertIntoManagedObjectContext: theContext)
newItem.mood = String(sender.tag)
newItem.date = dateFormat
}
} else { // No entries yet, I assume you want to add one...
let newItem = Mood(entity: theEnt!, insertIntoManagedObjectContext: theContext)
newItem.mood = String(sender.tag)
newItem.date = dateFormat
}
// Save Item
do {
try theContext.save()
} catch _ {
}
}
Note that (given your code newItem.date = dateFormat) I am assuming the date attribute is a string which you set using the same format ("YYYY/MM/dd"). This strips out the time information and so avoids the need for the date comparisons, but also has the advantage that a string sort is equivalent to a date sort (perhaps you chose that format for that reason). If date is in fact a Date attribute, the sort will still work but you will need to use a date comparison.
I use an NSDate extension for this.
extension NSDate {
class func areDatesSameDay(dateOne:NSDate,dateTwo:NSDate) -> Bool {
let calender = NSCalendar.currentCalendar()
let flags: NSCalendarUnit = [.Day, .Month, .Year]
let compOne: NSDateComponents = calender.components(flags, fromDate: dateOne)
let compTwo: NSDateComponents = calender.components(flags, fromDate: dateTwo);
return (compOne.day == compTwo.day && compOne.month == compTwo.month && compOne.year == compTwo.year);
}
}
Usage is like this.
if NSDate.areDatesSameDay(dateOne, dateTwo: dateTwo) {
// Dates are same day
} else {
// Dates are not the same day
}
#Tom Harrington Has just pointed out that you can use the NSCalendar methods to do this more simply
let calender = NSCalendar.currentCalendar()
if calender.isDate(dateOne, inSameDayAsDate: dateTwo) {
// Dates are same day
}
So we can make my lovely extension even simpler...
extension NSDate {
func isSameDayAs(date:NSDate) -> Bool {
let calender = NSCalendar.currentCalendar()
return calender.isDate(self, inSameDayAsDate: date)
}
}
Then use it like this.
if dateOne.isSameDayAs(dateTwo) {
// Dates are same day
} else {
// Dates are not the same day
}
And thats Numberwang!
I would like to check if a NSDate is before (in the past) by comparing it to the current date. How would I do this?
Thanks
I find the earlierDate method.
if date1.earlierDate(date2).isEqualToDate(date1) {
print("date1 is earlier than date2")
}
You also have the laterDate method.
Swift 3 to swift 5:
if date1 < date2 {
print("date1 is earlier than date2")
}
There is a simple way to do that. (Swift 3 is even more simple, check at end of answer)
Swift code:
if myDate.timeIntervalSinceNow.isSignMinus {
//myDate is earlier than Now (date and time)
} else {
//myDate is equal or after than Now (date and time)
}
If you need compare date without time ("MM/dd/yyyy").
Swift code:
//Ref date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let someDate = dateFormatter.dateFromString("03/10/2015")
//Get calendar
let calendar = NSCalendar.currentCalendar()
//Get just MM/dd/yyyy from current date
let flags = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
let components = calendar.components(flags, fromDate: NSDate())
//Convert to NSDate
let today = calendar.dateFromComponents(components)
if someDate!.timeIntervalSinceDate(today!).isSignMinus {
//someDate is berofe than today
} else {
//someDate is equal or after than today
}
Apple docs link here.
Edit 1: Important
From Swift 3 migration notes:
The migrator is conservative but there are some uses of NSDate that have better representations in Swift 3:
(x as NSDate).earlierDate(y) can be changed to x < y ? x : y
(x as NSDate).laterDate(y) can be changed to x < y ? y : x
So, in Swift 3 you be able to use comparison operators.
If you need to compare one date with now without creation of new Date object you can simply use this in Swift 3:
if (futureDate.timeIntervalSinceNow.sign == .plus) {
// date is in future
}
and
if (dateInPast.timeIntervalSinceNow.sign == .minus) {
// date is in past
}
You don't need to extend NSDate here, just use "compare" as illustrated in the docs.
For example, in Swift:
if currentDate.compare(myDate) == NSComparisonResult.OrderedDescending {
println("myDate is earlier than currentDate")
}
You can extend NSDate to conform to the Equatable and Comparable protocols. These are comparison protocols in Swift and allow the familiar comparison operators (==, <, > etc.) to work with dates. Put the following in a suitably named file, e.g. NSDate+Comparison.swift in your project:
extension NSDate: Equatable {}
extension NSDate: Comparable {}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
Now you can check if one date is before another with standard comparison operators.
let date1 = NSDate(timeIntervalSince1970: 30)
let date2 = NSDate()
if date1 < date2 {
print("ok")
}
For information on extensions in Swift see here. For information on the Equatable and Comparable protocols see here and here, respectively.
Note: In this instance we're not creating custom operators, merely extending an existing type to support existing operators.
Here is an extension in Swift to check if the date is past date.
extension Date {
var isPastDate: Bool {
return self < Date()
}
}
Usage:
let someDate = Date().addingTimeInterval(1)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
print(date.isPastDate)
}
In Swift5
let nextDay = Calendar.current.date(byAdding: .day, value: -1, to: Date())
let toDay = Date()
print(toDay)
print(nextDay!)
if nextDay! < toDay {
print("date1 is earlier than date2")
}
let nextDay = Calendar.current.date(byAdding: .month, value: 1, to: Date())
let toDay = Date()
print(toDay)
print(nextDay!)
if nextDay! >= toDay {
print("date2 is earlier than date1")
}
In Swift 4 you can use this code
if endDate.timeIntervalSince(startDate).sign == FloatingPointSign.minus {
// endDate is in past
}
we can use < for checking date:
if myDate < Date() {
}
Since Swift 3, Dates are comparable so
if date1 < date2 { // do something }
They're also comparable so you can compare with == if you want.
Upgrading Vagner's answer to Swift 5:
import Foundation
//Ref date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
//Get calendar
let calendar = NSCalendar.current
//Get just MM/dd/yyyy from current date
let flags: Set<Calendar.Component> = [Calendar.Component.day, Calendar.Component.month, Calendar.Component.year]
let components = calendar.dateComponents(flags, from: Date())
//Convert to NSDate
if let today = calendar.date(from: components), let someDate = dateFormatter.date(from: "03/10/2015"), someDate.timeIntervalSince(today).sign == .minus {
//someDate is berofe than today
} else {
//someDate is equal or after than today
}
Made a quick Swift 2.3 function out of this
// if you omit last parameter you comare with today
// use "11/20/2016" for 20 nov 2016
func dateIsBefore(customDate:String, referenceDate:String="today") -> Bool {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let myDate = dateFormatter.dateFromString(customDate)
let refDate = referenceDate == "today"
? NSDate()
: dateFormatter.dateFromString(referenceDate)
if NSDate().compare(myDate!) == NSComparisonResult.OrderedDescending {
return false
} else {
return true
}
}
Use it like this to see if your date is before today's date
if dateIsBefore("12/25/2016") {
print("Not Yet Christmas 2016 :(")
} else {
print("Christmas Or Later!")
}
Or with a custom reference date
if dateIsBefore("12/25/2016", referenceDate:"12/31/2016") {
print("Christmas comes before new years!")
} else {
print("Something is really wrong with the world...")
}