Swift 3: Working with dates

An early version of Swift 3 arrived along with the first beta of Xcode 8 a few days ago. Considered a preview release, this version of Swift 3 gives you a hint on the progress of the language evolution, but it also lets you taste the most thrilling thing about the new version IMO – the implementation of the new Swift API design guidelines. After toying around in a playground for a while, I have ended up with a small piece of code that deals with date objects – setting timezone, locale, extracting date components from a date and building a date from date components – all the trivial stuff that someone who deals with dates does.

The result is published in the gist below and one can’t help but notice how readable Swift 3 is without the verbosity of the old API and without the NS prefixes. I love Swift 2.2 but Swift 3 looks awesome.

2 thoughts on “Swift 3: Working with dates”

  1. func predicateForDayFromDate(date: NSDate) -> NSPredicate {
      let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
      var components = calendar!.components([.year, .month, .day, .hour, .minute, .second], from: date as Date)
      components.hour = 00
      components.minute = 00
      components.second = 00
      let startDate = calendar!.date(from: components)
      components.hour = 23
      components.minute = 59
      components.second = 59
      let endDate = calendar!.date(from: components)
                
      return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
    }

Leave a Reply

Your email address will not be published. Required fields are marked *