3

I've returned a NSDate value back from my server and I need to know how long ago this NSDate was. I need to write a conditional to see if the date is older than 6 months (in Swift, but I can convert Objective-C).

Here is the NSDate returned, when printed in console:

 (2015-09-07 01:22:01 +0000)

How do I check if this date above is older than 6 months?

The logic would be something like this:

//dateValue is the NSDate returned
var dateValue = log.createdAt
    if (dateValue > 6 months){
    }
    else{
    }
jscs
  • 63,694
  • 13
  • 151
  • 195
Josh O'Connor
  • 4,694
  • 7
  • 54
  • 98
  • Check those links, http://stackoverflow.com/questions/26198526/nsdate-comparison-using-swift and http://stackoverflow.com/questions/1889164/get-nsdate-today-yesterday-this-week-last-week-this-month-last-month-var – Ulysses Feb 19 '16 at 19:17
  • [Number of months and days between two NSDates](http://stackoverflow.com/q/11654741) – jscs Feb 19 '16 at 19:18

3 Answers3

6

Take a look at the NSCalendar class, and specifically methods like components:fromDate:toDate:options:.

If the 2 dates are different by 6 months and one day, is that > 6 months? How about 6 months and 1 second? Or do you only consider the 2 dates to be different by > 6 months if they differ by at least 7 months?

You would need to code your solution differently depending on the exact result you're after.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

Swift 3:

 if (nextStepDate.earlierDate(Date(timeInterval: -60*60*24*30*6, since: Date())) == date) {
     //do something                                         
 }
Josh O'Connor
  • 4,694
  • 7
  • 54
  • 98
-2
    if date.earlierDate(NSDate(timeInterval: -60*60*24*30*6, sinceDate: NSDate())) == date {
        // 6 months passed since date

    }
Etgar
  • 5,774
  • 2
  • 16
  • 30
  • OK, do you want to decrease this answer's point or to explain why it isn't good enough for you? – Etgar Feb 19 '16 at 19:21
  • 1
    I did not down-vote you, but that's not a good solution. The number of days varies from moth to month. Much better to use `NSCalendar` methods to compare the date, as suggested in my answer. – Duncan C Feb 19 '16 at 19:31
  • @Etgar, you said "365/2 days are good enough". It depends on the specific need, doesn't it? For some applications you might need to-the-day or even to-the-minute accuracy. – Duncan C Feb 19 '16 at 19:43
  • Thank you @Etgar. This actually works for me, since I only require a half a year. – Josh O'Connor Feb 19 '16 at 19:43
  • 1
    @Etgar 365/2 is a good approach but total days of six consecutive months should be in integer (Six months can't be 182.5 days..). Anyway, this question is all depends on how accurate you want. – Breek Feb 19 '16 at 19:44
  • By the way guys, I am only upvoting this answer && marking it as correct because it is the solution for MY problem.. This answer is incorrect if you want it more specific, as @Breek mentioned. Thanks guys :) – Josh O'Connor Feb 19 '16 at 19:46