search by tags

for the user

adventures into the land of the command line

dates in swift 2

Here’s some ways to manipulate dates with Swift 2

But first, date formats:

'Year: 'y' Month: 'M' Day: 'd            Year: 2016 Month: 6 Day: 30
dd/MM/yy                                 30/06/16
dd MMM, yyyy                             30 Jun, 2016
E MMM dd, yyyy                          Thu Jun 30, 2016
EEEE, MMMM dd, yyyy' at 'h:mm a.         Thursday, June 30, 2016 at 18:00 PM.
EEEE, MMMM dd, yyyy' at 'h:mm a zzzz.    Thursday, June 30, 2016 at 18:00 PM Central European Summer Time.

And how we create some date objects:

var basicDateObject:NSDate = NSDate()
var epochTimeObject:NSTimeInterval = NSDate().timeIntervalSinceReferenceDate

And how we create a date formatter:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

Converting a date object to a string

let dateObject = NSDate()
dateFormatter.dateFormat = "d MMM, yyyy"
let dateString = dateFormatter.stringFromDate(dateObject!)

Converting a string to a date object

let dateString:String = "2016-06-30"
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateObject = dateFormatter.dateFromString(dateString!)

Converting a date object in the form of an epoch time to a string

let dateString = "30 Jun, 2016"
dateFormatter.dateFormat = "d MMM, yyyy"
let formattedDate = dateFormatter.stringFromDate(NSDate(timeIntervalSinceReferenceDate: dateString))

Converting a string to a date object in epoch time

let someDateString = "2016-06-30"
dateFormatter.dateFormat = "yyyy-MM-dd"
let someDateObject = dateFormatter.dateFromString(someDateString!)!.timeIntervalSinceReferenceDate

Converting a date object to an epoch

let someDateObject = NSDate()
let someEpochTime = someDateObject.timeIntervalSinceReferenceDate

Best way to compare dates to find which is larger or smaller, earlier or later, older or younger? Use NSTimeInterval data types.

if someDateObject.timeIntervalSinceReferenceDate >= someOtherDateObject.timeIntervalSinceReferenceDate {
  do something funky
}

There’s way more obviously, but this is all I’ve been using thus far. I’ll add more to this list as I encounter it.