-1

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)")
        }
    }

}
nhgrif
  • 61,578
  • 25
  • 134
  • 173
Zach
  • 180
  • 1
  • 2
  • 12
  • Step 1: Extract your *actual* problem out into the most minimal example that duplicates what you are trying to do. I don't understand what you mean when you say you're trying to **set NSDate < NSDate**... that doesn't make sense. So... to help it make sense, make a smaller example, don't just copy & paste out of your project. – nhgrif Apr 26 '15 at 21:10
  • possible duplicate of [How to compare two NSDate objects in objective C](http://stackoverflow.com/questions/8183472/how-to-compare-two-nsdate-objects-in-objective-c) – Paulw11 Apr 26 '15 at 21:10
  • Be aware that your method of creating the "expire date" will be exactly 24 hours from now - so if it is 1:39 in the afternoon, expire date will be 1:39 tomorrow afternoon. If you wanted "midnight today" through "midnight tomorrow" you will need a different approach – Paulw11 Apr 26 '15 at 21:38
  • Thank you guys. Paul I would like it to be exactly 24hrs, thank you though! – Zach Apr 26 '15 at 22:13
  • Actually, @Paulw11, what you've said is only partially correct. It will only be 1:39 tomorrow afternoon if we didn't go through a DST time change, or any sort of leap second... or all the other complicated things that time does. – nhgrif Apr 26 '15 at 23:03
  • `var expireDate = NSDate(timeIntervalSinceNow: -60 * 60 * 24)` and `post.createdAt! > expireDate` – Tobias Apr 27 '15 at 00:04

4 Answers4

3

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
}
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • With this method, it still adds annotations for pins older than 24hrs. I want all pins 24hrs or younger to be displayed, maybe my code is wrong. I have updated my original post with the code im using – Zach Apr 26 '15 at 23:00
  • @Zach Again, *please*, recreate your *exact* problem with the most minimal example possible. Do this and you'll probably see the problem yourself without needing Stack Overflow. – nhgrif Apr 26 '15 at 23:04
  • I appreciate that, I apologize im new to this. I figured posting the whole code would help others see what im doing fully and what I am aiming to accomplish. I will update it now – Zach Apr 26 '15 at 23:06
  • 1
    @Zach First, **please** roll your code back to the version that my answer actually addresses. You've completely invalidated my answer with your edits and make my answer look silly and pointless. Stop editing your question. Just stop. Take a breather. Take 24... 48... heck, 72 hours... try to actually break your problem down. Don't just throw the whole glob of code up on the web and hope someone will have all your answers. You'll never learn doing it this way. Remove all the junk that has nothing to do with your problem. Reproduce your problem in the simplist way possible. – nhgrif Apr 26 '15 at 23:08
  • 1
    This is a very rudimentary debugging skill. This isn't just something that we request people do for the sake of Stack Overflow. It's a crucial step in debugging any problem. Reproduce the problem with the simplest possible example so we can narrow down what is and isn't relevant to the problem. *Most* of the time, in doing this, the problem because so obvious you'll feel stupid for not seeing it sooner. – nhgrif Apr 26 '15 at 23:10
-1

Use:

if (current.timeIntervalSince1970() < expireDate.timeIntervalSince1970()) {
    self.mapView.addAnnotation(annotation)
}

instead.

Ayan Sengupta
  • 5,238
  • 2
  • 28
  • 40
-1

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 :)

Yuyutsu
  • 2,509
  • 22
  • 38
-2

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. :)

bhakti123
  • 833
  • 10
  • 22
  • A link only is not much use, and the OP has already said that he knows that it's not an Int. Other answers have pointed out the correct method on NSDate to call. – Abizern May 20 '16 at 16:51
  • And what does this add over the answer that was given over a year ago. – Abizern May 20 '16 at 17:03