A Beginner’s Guide to NSDate in Swift

If I was ever asked what’s one of the most common stuff I do among all projects, then I would have answered that dealing with dates is definitely one of them. Undoubtably, there’s no developer out there who doesn’t really need to “play” with the NSDate class and handle dates in some manner, no matter how much or little the work on dates is. From simply converting a date value into a string up to performing calculations with dates, there’s always one constant fact: Developers have to be acquainted with this side of programming in iOS. It’s not hard to master, and eventually can lead in gaining time in other more important programming tasks. Working with dates might seem like a hassle to new programmers; however that’s not true. All you need is to get the grasp of it.

The most common operation when using date (NSDate) objects in applications, is to convert them into string objects so they can be properly formatted and shown to the users. Quite common is the reverse action as well; converting strings to date objects. However, these are not the only tasks regarding dates. Here’s a sample list of what else can be done when messing with dates:

  • Compare dates.
  • Calculate dates in the future or in the past, simply by using a reference date (e.g. the current date) and adding or subtracting periods of time (days, months, years, etc).
  • Calculate date differences (e.g. find the elapsed time between two specific dates).
  • Break a date into its components and access each date part separately (day, month, etc).

All the above, including the conversions to and from strings, are subject for discussion in this tutorial. Through the next parts, you’ll see that is actually easy to do whatever you wish with dates, as long as you know what your tools are and how you should use them.

For your reference, I give you next a list of links with some important documentation. Don’t forget to pay a visit in case you need more information on specific topics:

Continue reading my tutorial on Appcoda