Compare, addition, subtraction & countdown with NSDate

This tutorial is updated for X code 7.3 & swift 2.2

Arithmetic operations on date is very important in iPhone apps. Because user input date once then its displayed in number of different ways. I am not just talking about formatting of the date. With simple arithmetic operations you get lot more information for example with taking birthday as input you can find out what is their age. How many days till next birthday & so on.

Compare NSDate

We are going to learn 3 ways to compare two dates. First we are going to create dates using components. For illustration purposes I am taking two dates Mother’s Day 2016 & Father’s Day 2016. I am creating dates as follows

let userCalendar = NSCalendar.currentCalendar()

let mothersDayComponent = NSDateComponents()

mothersDayComponent.year = 2016

mothersDayComponent.month = 5

mothersDayComponent.day = 8

let mothersDay = userCalendar.dateFromComponents(mothersDayComponent)!

let fathersDayComponent = NSDateComponents()

fathersDayComponent.year = 2016

fathersDayComponent.month = 6

fathersDayComponent.day = 19

let fathersDay = userCalendar.dateFromComponents(fathersDayComponent)!

Now I am going to start comparing dates as follows

let earlierDate = mothersDay.earlierDate(fathersDay)

print(earlierDate)

let laterDate = mothersDay.laterDate(fathersDay)

print(laterDate)

As the name suggests earlier date tells us which date comes first & later date tells us which date comes last. But the result we get here is actual NSDate. Result in debug area looks like follows

date compare

Another way to compare two date is as follows

var compareResult = mothersDay.compare(fathersDay)

switch compareResult {

case NSComparisonResult.OrderedAscending:
print(“Mothers day comes before fathers day”)

case NSComparisonResult.OrderedDescending:
print(“Mother’s day comes after fathers day”)

case NSComparisonResult.OrderedSame:
print(“Mother’s day is on same day as father’s day”)

}

With this method you get additional result if both dates are same. In previous method this was not possible. In previous method you get NSDate as result. You have no way of knowing which date has won.

If you want more granular control on comparing two dates then you can do it as follows

var compareResult = userCalendar.compareDate(mothersDay, toDate: fathersDay, toUnitGranularity: NSCalendarUnit.Year)

switch compareResult {

case NSComparisonResult.OrderedAscending:
print(“Mothers day comes before fathers day”)

case NSComparisonResult.OrderedDescending:
print(“Mother’s day comes after fathers day”)

case NSComparisonResult.OrderedSame:
print(“Mother’s day is on same year as father’s day”)

}

In above method we are checking if both date fall within same year or not. Using same method we can find out if both dates fall within same day, week, hour, minute or second. This method gives you more accurate way of comparing two dates.

Addition NSDate

In real world example most commonly you just want to change one unit of the date. For example a week from now, month from now or 10 days from now. See the following code

if let fiveDaysFromNow = userCalendar.dateByAddingUnit(NSCalendarUnit.Day, value: 5, toDate: NSDate(), options: []) {
let dateformatter = NSDateFormatter()

dateformatter.dateStyle = NSDateFormatterStyle.MediumStyle

dateformatter.timeStyle = NSDateFormatterStyle.NoStyle

print(dateformatter.stringFromDate(fiveDaysFromNow))

}

When you print the date its in UTC time & it’s difficult to figure out if this worked or not. Hence I am converting date in String. At the time of writing this tutorial the date is December 26th 2015. Just a day after christmas. I am adding 5 days to it. And I get following result.

Screen Shot 2015-12-26 at 4.00.15 PM

Limitation of method above is that you can add to only one unit of the date. If you want to add day, hour, minute then use following code.

let addingPeriod = NSDateComponents()

addingPeriod.day = 5

addingPeriod.hour = 7

addingPeriod.minute = 15

if let newYearsParty = userCalendar.dateByAddingComponents(addingPeriod, toDate: NSDate(), options: []) {
let dateformatter = NSDateFormatter()

dateformatter.dateStyle = NSDateFormatterStyle.MediumStyle

dateformatter.timeStyle = NSDateFormatterStyle.ShortStyle

print(dateformatter.stringFromDate(newYearsParty))

}

In above code I am adding multiple units to Current date. To keep it simple I am using today’s date. But you can insert any date of your choice & it will add multiple components. The output in debug area is as follows

Screen Shot 2015-12-26 at 4.06.58 PM

Challenge 1: Subtract today’s date from next birthday & display remaining days.

days remaining
Download Challenge 1 Playground file
Challenge 2: Subtract today’s date from next birthday & display countdown.

countdown
Download Challenge 2 Playground file

Total 3 Votes
0

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?