Working with UIDatePicker and NSDateFormatter

If all goes well, the app that I’m working on will allow users to schedule local notifications for specific days and times. Since I’ve never worked with dates in iOS before (yep, I’m that much of a beginner), I went searching for some resources that could help me get started. I was hoping to create something like the “Info” screen in the official Reminders app, where users can toggle “Remind me on a day” and set an alarm using a scrolling date picker.

One thing I like about that screen in Reminders is that the table row that displays the date and time formats it in two different ways. When the date picker is closed, the date is abbreviated like so: “Wed, 4/1/2015, 3:00 PM.” When the date picker is expanded, the date changes to a longer format: “Wednesday, Apr 1, 2015, 3:00 PM.”

Date Picker

I decided to tackle the date formatting issue first. Fortunately, I stumbled upon a great article that describes exactly how to format dates using NSDateFormatter and Swift. There are four built-in style presets that can apply to both dates and times. Unfortunately, none of presets resembled what I saw in the Reminders app, so I moved on to the “Custom Fixed NSDateFormatter Styles” section. From there, I came up with the following two styles:

The next step was to figure out how to change my dateLabel to display the selected date from the Date Picker. For that, this handy tutorial did the trick. Next, I used a boolean value to determine whether or not the Date Picker was expanded and adjusted the format of the date string accordingly. My result looked almost identical to the Reminders app, which is exactly what I wanted! Why reinvent the wheel?

My Date Picker

Diving into a real project that I care about was the best decision I could have made, and I definitely recommend it. You’ll learn so much more!