Mid-2013 and Apple still hasn't provided a simple way to set a NSDate value.
During my current iPad project, I couldn't believe I had to stop productivity for a while to write my own helper class to get the Year value from an NSDate. I mean, come on, this is basic stuff.
Anyway, here's the helper class I used in my project, to convert a string into an NSDate value :
My solution had been to use the following code, but I found that sometimes, it just wouldn't parse, and would return nil.
// Take a date string in the format "Oct 23, 2013", and convert it into a NSDate value
// THIS DOESN'T WORK ! DON'T TRUST THIS CODE !!
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd, yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate* date = [formatter dateFromString:dateString];
I remember it failed miserably on "Oct 12, 2012"... which is why I gave up and used the more complicated "parseDateString" function shown above.
My point is... be careful.
Some of the very-basic NSDate functions just don't work properly...
I found this thread while looking for an answer to this question but then I found a good example in one my Big Nerd Ranch Objective-C Programming book. Credit to them, not me.
Examples are often the easiest way to learn. Here are a few examples.
Now
This one is the easiest.
let currentDateTime = Date()
February 20, 2017
// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 2017
dateComponents.month = 2
dateComponents.day = 20
// Create date from components
let userCalendar = Calendar.current // user calendar
let dateThisPostWasUpdated = userCalendar.date(from: dateComponents)
April 1, 1976
// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1976
dateComponents.month = 4
dateComponents.day = 1
// Create date from components
let userCalendar = Calendar.current // user calendar
let appleFoundedDate = userCalendar.date(from: dateComponents)
Need more details...?
There are other ways to create dates, too. If you want to learn those, as well as how to display a date, then see my fuller answer.