Search This Blog

Wednesday, March 30, 2016

TimeSince

My second app, TimeSince, is now available on the App Store! It's free, so please check it out and leave a review!

Wednesday, March 2, 2016

Code Sample: Sorting an Array of Dates as Strings

My WeightLifts app used a LOT of date comparisons to make everything show up in the right order. Sorting an array of Date strings seemed to be something everyone knew how to do except me. It was only after a LOT of searching and trial and error, did I figure it out. 

To save you all the headache, here is a code sample showing how to do it. Copy and paste this into a playground and it should work.  This code is written in Swift 2.0 by the way.

import UIKit

func convertStringDateToNSDateAndSort(unsortedDateArray:[String]) -> [String] {
    
    //Strings cannot be sorted by date, so we need an array of NSDate Objects instead
    var dateObjectArray: [NSDate] = []
    
    //create another array to hold the sorted dates as strings
    var sortedDateArray:[String] = []
    
    
    //create an NSDateFormatter that will convert a string to an NSDate
    let dateStringFormatter = NSDateFormatter()
    
    //you can set the format to your preference, I have chosen the MMMM dd, yyyy format
    dateStringFormatter.dateFormat = "MMMM dd, yyyy"

    //now, go through each item in the unsortedDateArray and convert it to an NSDate
    for DateString in unsortedDateArray {
        let dateAsNSDate = dateStringFormatter.dateFromString(DateString)
        dateObjectArray.append(dateAsNSDate!)
        
    }
    
    //by this point you will have an unsorted array of NSDate objects. These CAN be sorted, and sorted without creating another array (i.e, sorted in place). The code below basically says "compare each item in dateObjectArray in pairs. If the first item is more recent than the second, move it to the front of the array.
    
    dateObjectArray.sortInPlace{(item1, item2) -> Bool in
        return item1.timeIntervalSinceNow > item2.timeIntervalSinceNow
    }
    
    //by this point, you will have an array of sorted NSDate objects. Create another NSDateFormatter to change them BACK into Strings.
    let dateFormat = NSDateFormatter()
    dateFormat.setLocalizedDateFormatFromTemplate("yyyyMMMMdd")
    
    //now go through each object in the dateObjectArray, convert them to strings, and append them to the sortedDateArray
    for dateItem in dateObjectArray {
        let dateItemToAppend = dateFormat.stringFromDate(dateItem)
        sortedDateArray.append(dateItemToAppend)
        
    }
    
    //now return the sortedDateArray
    return sortedDateArray
}

var ArrayContainingUnsortedDatesAsStrings = ["April 1, 2009", "February 5, 2013", "December 19, 2006"]

var ArrayOfSortedDatesAsStrings = convertStringDateToNSDateAndSort(ArrayContainingUnsortedDatesAsStrings)

print(ArrayOfSortedDatesAsStrings)

What you'll end up with is:

["February 05, 2013", "April 01, 2009", "December 19, 2006"]