swift dateformatter class

Click the diagram to see it at full size.

In the previous article in this series, we looked at three key structs for date and time programming in Swift:

  • Date represents a single point in time, using a format that can easily be translated into just about any calendar and time-reckoning system: a number of seconds relative to the start of the Third Millennium (January 1, 2001, 00:00:00 UTC).
  • DateComponents specifies time units like year, month, day, hour, minute, and more to represent either a point in time or a duration of time.
  • Calendar provides a context for Dates, and converts Dates to DateComponents and DateComponents to Dates.

These structs all deal with the internal representation of dates and times. In this article, we’ll look at the DateFormatter class, which allows us to deal with their external representation — by converting Dates into Strings, and properly-formatted Strings into Dates.

Let’s convert a Date into a String, part 1: Just the date

alexander graham bell and phone

Start a new playground and enter the following code, which gives us a Date that we can format — the day when Alexander Graham Bell made the very first phone call:

Now let’s try turning this date into a string with a DateFormatter:

You may be surprised that the result is an empty String. This can be fixed by specifying a dateStyle:

Let’s try the other dateStyles:

Why would there be a dateStyle called .none? I’ll explain in a little bit.

Let’s convert a Date into a String, part 2: A date and a time

steve jobs and ipad

Let’s work with an event for which we know both the date and time: the “Stevenote” where the iPad was introduced, which started on January 27, 2010, at 10:00 a.m. Pacific Time (UTC-8). We’ll define this as a Date by adding the following code:

Now that we have a date and time, let’s format it using the dateStyle and timeStyle properties:

Now that we’re working with a date and time, let’s see what the .none style is for:

Remember that in Swift, the Date struct represents a single point in time, which has both a date and a time. The .none style for DateFormatter‘s dateStyle and timeStyle properties allows us to create a String representation of a Date that shows only its date or time part.

Let’s convert a Date into a String, part 3: Custom date/time formats

electronic calendar

Before we begin working with custom date/time formats, I should point out that if you need to display a Date as a String to the user, it’s best if you use Swift’s built-in dateStyle and timeStyle values. They display dates and times properly, according to the user’s settings, which include country and language. You’d be surprised how date formats differ from culture to culture, and it’s better to let Swift do the formatting work.

However, there are times when you need to format dates and times in a specific way that doesn’t match the styles provided by DateFormatter‘s dateStyle and timeStyle properties, such as when dealing with certain APIs. That’s where DateFormatter‘s dateFormat property comes in handy:

You can use the date format specifiers listed in Appendix F of the Unicode Technical Standard #35 to define the formatting String for the dateFormat property. Here are some examples:

Let’s convert a String into a Date

clock and calendar

DateFormatter works the other way — just as it can convert Dates to Strings, it can also convert Strings to Dates. By setting its dateFormat to the format of the String it should expect, you can use its date(from:) method to convert a String into a Date:

Let’s change the dateFormat string and try it again:

Wrapping it all up

Here’s a playground containing all the code we just worked with:

In the next installment, we’ll look at date calculations.

{ 3 comments }

Pokémon Go and workplace data security

pokemon go

With over 25 million users playing every day, and downloads and active users surpassing even Twitter and Tinder, Pokémon Go is turning out to be one of the most popular mobile applications of all time. According to Data Security Law Blog, it also highlights the risks in BYOD (Bring Your Own Device) policies.

With a BYOD device that has Pokémon Go installed, the risks come from the security — or more accurately, insecurity — of the Pokémon Go app itself. Earlier versions of the game gave the app full access to the user’s complete Google account profile and related information, including Google-accessible email accounts and search history. While it’s not likely that this now-fixed security hole led to any breaches, it’s a prime example of how a suddenly popular app running on a BYOD device can lead to trouble.

All this is still new territory — the smartphone as we currently know it won’t even turn 10 until next year — and businesses would do well to watch the effects of apps like Pokémon Go, and alter their mobile policies accordingly.

The pros and cons of BYOD

byod

As we’ve observed before, mobile devices are more personal than even “personal” computers. People don’t want to part with them, which is why they prefer to bring them to work — and use them for work. This attachment to our mobile devices, for which we’re finding more and more uses, is why at least two-thirds of employees are using their own mobile devices in the course of doing their jobs.

Tech.co has a brief but useful article that summarizes the big pros and cons of BYOD, explains what the general best practices are, and explains why training employees is key to a successful BYOD implementation. If your organization is considering or just starting with a BYOD program, it would be worth your time to read this article.

The 11-step guide to BYOD security, or how to avoid getting fired

security

In a recent entry on their blog, Heimdal Security provide these BYOD statistics:

In the same article, they list eleven common sense (which is uncommon) steps for BYOD users to secure the personal mobile devices they use for work. As they say, “security is each user’s own business”.

this article also appears in the GSG blog

{ 0 comments }

The next Tampa iOS Meetup, and upcoming changes

by Joey deVilla on August 19, 2016

change

It’s been a couple of months since the last Tampa iOS Meetup, and with summer drawing to a close and iOS 10 coming very soon, it’s time to kick things back into high gear. It’s going to be an interesting fall, what with the coming changes…

bay to bay

angelaThe first change is that Angela, who originally put this Meetup group together, landed a job in San Francisco and moved there. I want to congratulate her on seizing this opportunity — I did the same thing during the dot-com bubble of the late ’90s — and wish her the very best in her adventures in the other Bay Area. I’d also like to thank her for all the work she’s done for this Meetup group, which wouldn’t even exist without the initial spark that she provided.

As for me, I plan to stick around, and will continue in my role as this Meetup group’s organizer, lead speaker, and accordion player.

building imessage sticker packs and messaging apps for ios 10

The next change comes from Apple, in the form of iOS 10, Xcode 8, and Swift 3, and we’ll be talking about what these new versions mean for you as iOS developers over the next couple of meetups.

The date for the next meetup is to be determined, but I’m aiming for early September, and the topic will be Building iMessage sticker packs and messaging apps for iOS 10. iMessage is one of the most-used iOS apps, and a lot of people seem to like adding a little flair to their communications, so the introduction of sticker packs and iMessage apps represents an opportunity for the developer looking to make a splash. Sticker packs have the added bonus of not needed any programming to develop.

samsung galaxy s7 and iphone 6s

The final change is one that I’d like your opinion on. I’m thinking of expanding the subject area of our Meetup group to cover these topics:

  • iOS development, which it already covers,
  • Android development,
  • and IoT (internet of things) development

In other words, I’m thinking about expanding our group’s coverage to while I like calling development for “Tiny shiny platforms”. Would this be something that you’d be interested in, or would you rather stick to just iOS? I’d love to hear what you think — let me know by dropping me a line at joey@joeydevilla.com­!

{ 0 comments }

changing stuff and seeing what happens

It’s how we learn best, so go forth, experiment, watch what happens, take notes — and if you can, share your knowledge. Happy hacking!

The image above comes from @ThePracticalDev’s Twitter account, and I used it in a recent article: How to work with dates and times in Swift 3, part 1: Dates, Calendars, and DateComponents.

{ 0 comments }

i just want to use dates

If you’re just getting started with date and time programming in Swift 3, chances are that you probably did some Googling, found something about NSDate and its companion classes in Apple’s documentation and promptly got confused. Let me reassure you that it isn’t your fault.

For starters, a lot of the documentation out there is in Objective-C, which can throw you off if you’re not familiar with its [instance method: parameter2: parameter3:] method-calling syntax. There’s also the fact that Apple recently removed the NS prefix from Cocoa’s class names — NSDate is now just plain ol’ Date, NSCalendar is now Calendar, NSDateComponents is now DateComponents, and so on. And finally, in the move towards protocol-oriented programming, Apple has changed some classes to structs, including many of the classes for working with dates and times.

And finally, if you’re coming to Swift 3 from JavaScript, which makes do with a single object type called Date, the idea of having this set of classes just to handle dates and times looks like overkill:

swift 3 date and time classes

Click the diagram to see it at full size.

In this series of articles, we’ll look at date and time programming in Swift 3. By its end, you’ll have a firm grasp on the topic.

Swift’s Date struct represents dates and times

swift date struct

Click the diagram to see it at full size.

In Swift, dates and times are represented by instances of Date, which is a struct. Date is independent of any time zone, or even any calendar system. It gets this independence through the way it represents time: as a number of seconds relative to the start of the Third Millennium, January 1, 2001, 00:00:00 UTC.

The following playground code shows the various ways of creating Dates:

Of course, we don’t think of dates and times in terms of seconds relative to the start of the Third Millennium, or the start of the Unix Epoch, or any other arbitrary date and time. That’s why Swift features a couple of other structs to help us make sense of Dates: Calendar and DateComponents.

Calendars give dates context, DateComponents let us assemble dates or break dates apart

swift calendar struct

Click the diagram to see it at full size.

Think of the Calendar struct as a way to view Dates in a way that makes more sense to us: not as a number of seconds before or after January 1, 2001 00:00:00 UTC, but in terms of a year, month, day, hour, minute, and more.

The Calendar struct supports 16 different calendar systems, including the Gregorian calendar (a.k.a. the Western or Christian calendar), which is likely the one you use the most. Consider Swift’s reference date:

  • In a Date struct, its value is 0.
  • In the Gregorian calendar, this date has the following values:
    • Year: 2001
    • Month: 1
    • Day: 1
    • Hour: 0
    • Minute: 0
  • In the Hebrew calendar, this date has the following values:
    • Year: 5761
    • Month: 4
    • Day: 6
    • Hour: 0
    • Minute: 0
  • In the Buddhist calendar, this date has the following values:
    • Year: 2543
    • Month: 1
    • Day: 1
    • Hour: 0
    • Minute: 0

In most apps, you’ll likely be using the Gregorian calendar, so Calendar‘s real use is to convert Dates into DateComponents, and DateComponents into Dates:

swift datecomponents struct

Click the diagram to see it at full size.

The DateComponents struct is an assembly of properties that make up a date, such as year, month, date, hour, minute, second, and so on. DateComponents instances can be used to represent either a specific point in time, or a duration of time.

Using both Calendar and DateComponents structs, we can perform these key actions:

  • Build Dates using properties such as year, month, day, hour, and minute rather than a number of second relative to a reference date, and
  • extract properties from Dates, such as year, month, day, hour, and minute.

Let’s start creating some Dates with the help of Calendar and DateComponents.

Let’s create a Date given a year, month, and day, part 1

alexander graham bell

Let’s start with the first date in phone history: March 10, 1876, the day when Alexander Graham Bell made the first phone call. Create a new playground and enter or paste the code below:

In the code, we:

  • Get the user’s current Calendar.
  • Create an DateComponents struct, firstLandPhoneCallDateComponents, providing values for the year, month, and day parameters, and nil for all the others.
  • Use the user’s Calendar to create firstLandPhoneCallDate using firstLandPhoneCallDateComponents.
  • Get the internal representation of the Date.

Here’s a screenshot of the playground code as seen on my computer, whose time zone is set to “US/Eastern” (UTC-5):

firstlandphonecalldate

Click the screenshot to see it at full size.

Note the results in the sidebar at the lower right-hand corner:

  • firstLandPhoneCallDate‘s value corresponds to the DateComponents properties we set: March 10, 1876, 12:00 a.m..
  • firstLandPhoneCallDate‘s internal value, contained within its timeIntervalSinceReferenceDate property, is -3,938,697,748, which indicates that Alexander Graham Bell’s inaugural phone call was made nearly 4 billion seconds prior to the start of the Third Millennium.

Let’s create a Date given a year, month, and day, part 2

martin cooper

Let’s try creating another momentous date in phone history: the day when Martin Cooper made the first cellular phone call, April 3, 1973. We’ll do it differently this time, by creating a blank DateComponents struct, and then setting its year, month, and day properties. Add the following code to the code above:

In the code, we:

  • Create an empty DateComponents struct, firstCellPhoneCallDateComponents.
  • Set the year, month, and day properties of firstCellPhoneCallDateComponents to correspond to the date April 3, 1973.
  • Use the user’s Calendar to create firstCellPhoneCallDate using firstCellPhoneCallDateComponents.
  • Get the internal representation of the Date.

Here’s a screenshot of the results:

firstcellphonecalldate

Click the screenshot to see it at full size.

Let’s create a Date: What date does National Donut Day — the first Friday in June — fall on in 2017?

Having come from Canada, the country with the world’s highest per capita donut shop concentration and the people who eat the most donuts per capita, I can assure you that National Donut Day has been a real thing since 1938. It takes place on the first Friday in June, and we can find out what date it falls on in 2017 — or any other year — through the judicious use of DateComponents properties.

Add the following code to the current playground:

You should be familiar with the year and month DayComponents properties by now, and we’re using a couple that may be new to you:

  • weekday: Specifies a day of the week. With the Gregorian calendar, valid values are 1 through 7, where 1 is Sunday, 2 is Monday, 3 is Tuesday, and so on. Since we’re looking for a Friday, we’ve set this value to 6.
  • weekdayOrdinal: Specifies the order of the given weekday in the next larger specified calendar unit. Since we set weekday to 6 and set this value to 1, and since the next largest specified calendar unit was month, we’ll get the date of the first Friday of the month.

If you check the value of donutDayDate in the playground’s sidebar, you should see Jun 2, 2017, 12:00 AM. If you look at a calendar, you’ll confirm that it is indeed the first Friday of June 2017.

changing stuff and seing what happens

In the spirit of the fake book cover shown above, let’s see what happens if we don’t specify the month. Comment out the following line from the code you just added…

donutDayComponents.month = 6

…so that the code now looks like this:

When you run the code, you’ll see that the date for donutDayDate is now Jan 6 2017, 12:00 AM. Now that we’re specifying only a year and not a month, Swift interprets the combination of donutDayComponents.weekday = 6 and donutDayComponents.weekdayOrdinal = 1 to mean “the first Friday of the year”. If you look at a calendar, you’ll confirm that January 6, 2017 is indeed the first Friday of the year.

Let’s create one more Date: 5:00.pm. on Thursday of the 18th week of 2017…in Tokyo.

The great thing about Swift’s Calendar class is that it does its best to work with the DateComponents that you give it, and DateComponents gives you all sorts of ways to specify a date. Let’s assume for a moment that you’re in Japan and want to leave work at the ridiculously early hour of 5 p.m. and have some relaxing Suntory times, and it just happens to be the 18th week of 2017. What’s the date?

The answer comes from this code:

On my system, which is in the Eastern daylight time zone (UTC-4) at the time of writing, thursday5pm18thWeek2017TokyoDate displays as May 4, 2017, 4:00 AM in my playground’s sidebar, and looking at a calendar confirms that May 4th is indeed the Thursday of the 18th month of 2017.

Let’s extract DateComponents from a Date, part 1

Now that we’ve created some Dates using DateComponents, let’s do the reverse and extract DateComponents from given Dates. We’ll continue with our playground and use a Date we’ve already created: firstLandPhoneCallDate, which corresponds to the date of Alexander Graham Bell’s historic phone call, March 10, 1876. Here’s code that extracts the year, month, and day from this Date:

Let’s extract DateComponents from a Date, part 2

This time, let’s create a new Date — one that corresponds to this key date in iOS history: the “Stevenote” where the original iPhone was first announced:

If you were to ask Swift when this Stevenote took place, it would reply “190,058,400 seconds after the reference date”. For most of us, this is a meaningless figure, so we’ll extract the following DateComponents from this Date:

  • Year
  • Month
  • Day
  • Hour
  • Minute
  • What day of the week this Date fell on
  • What week of the year this Date fell on

Here’s the code:

Let’s extract DateComponents from a Date, part 3

Let’s try it again with another key iOS date — the Stevenote where the original iPad was announced:

This time, if you were to ask Swift when this Stevenote took place, it would reply “286,308,000 seconds after the reference date”. Let’s get all the DateComponents for this date:

Let’s take a look at each DateComponents property and what it represents:

Property Description
calendar The calendar system for the date represented by this set of DateComponents. We got these DateComponents by converting a Date using a Gregorian Calendar, so in this case, this value is gregorian.
day The day number of this particular date and time. For January 27, 2010, 18:00:00 UTC, this value is 27.
era The era for this particular date, which depends on the date’s calendar system. In this case, we’re using the Gregorian calendar, which has two eras:

  • BCE (a.k.a. BC), represented by the integer value 0
  • CE (a.k.a. AD), represented by the integer value 1
hour The hour number of this particular date and time. For January 27, 2010, 18:00:00 UTC, this value is 13, because in my time zone, 18:00:00 UTC is 13:00:00.
minute The minute number of this particular date and time. For January 27, 2010, 18:00:00 UTC, this value is 0.
month The month number of this particular date and time. For January 27, 2010, 18:00:00 UTC, this value is 1.
nanosecond The nanosecond number of this particular date and time. For January 27, 2010, 18:00:00 UTC, this value is 0.
quarter The quarter number of this particular date and time. January 27, 2010, 18:00:00 UTC, is in the first quarter of the year, so this value is 0.
second The second number of this particular date and time. For January 27, 2010, 18:00:00 UTC, this value is 0.
timeZone The time zone of this particular date and time. I’m in the UTC-5 time zone (US Eastern), so this value is set to that time zone.
weekday The day of the week of this particular date and time. In the Gregorian calendar, Sunday is 1, Monday is 2, Tuesday is 3, and so on. January 27, 2010, was a Wednesday, so this value is 4.
weekdayOrdinal The position of the weekday within the next larger specified calendar unit, which in this case is a month. So this specifies nth weekday of the given month. Jauary 27, 2010 was on the 4th Wednesday of the month, so this value is 4.
weekOfMonth The week of the month of this particular date and time. January 27, 2010 fell on the 5th week of January 2010, so this value is 5.
weekOfYear The week of the year of this particular date and time. January 27, 2010 fell on the 5th week of 2010, so this value is 5.
year The year number of this particular date and time. For January 27, 2010, 18:00:00 UTC, this value is 2010.
yearForWeekOfYear Oh wow, this is so hard to explain that I’ll leave it to Apple’s docs.

Wrapping it all up

Here’s the playground containing all the code we just worked with:

In the next installment, we’ll look at converting Dates to Strings, and vice versa.

{ 6 comments }

The truth about typefaces

by Joey deVilla on August 10, 2016

IMG_2593

This one goes out to all the front-end and interface designers and developers out there.

{ 0 comments }

raspberry pi 12

Click the photo to see it at full size.

On the most recent Amazon Prime Day — an annual trick that Amazon pulls in order to boost sales in the same vein as Cyber Monday, but in the summer — I managed to limit myself to buying just one sale-priced thing that I didn’t really need: the CanaKit Raspberry Pi 3 Complete Starter Kit. It normally sells on Amazon for US$75, but it was on sale that day for US$60.

The Raspberry Pi 3 is the current version of a series of single-board computers about the size of a deck of playing cards, and are:

I plan to use the Raspberry Pi to make some initial delving into IoT (Internet of Things) development, and as part of my journey into developing for that category of computer that I call “tiny and shiny” — smartphones, tablets, and now Raspberry Pi / Arduino-type boards.

Here’s the CanaKit Raspberry Pi 3 Complete Start Kit box:

raspberry pi 01

When I opened it, I saw this:

raspberry pi 02

The first thing you should see is a greeting card that also provides an email address for assistance, should you need it. The other side of the card has a diagram explain what each of the GPIO interface pins on the Raspberry Pi 3 board is for.

Below the card was an HDMI cable:

raspberry pi 03

And below that were three boxes:

raspberry pi 04

From largest to smallest, the three boxes contained the Raspberry Pi 3 board and SD card (which functions as its “hard drive”)…

raspberry pi 05

…a case for the board…

raspberry pi 06

…and a power supply for the board:

raspberry pi 07

Below the boxes were these items:

raspberry pi 08

One bag contained a USB microSD card reader. It allows you to use your regular computer to download updated or different versions of the Raspberry Pi OS or software and transfer them onto the microSD card:

raspberry pi 09

The other bag contained two heatsinks for its chips. They already have heatsink adhesive attacked to them; you just have to peel off the backing and stick them onto their respective chips:

raspberry pi 10

At the bottom of the box was the “quick start” guide:

raspberry pi 11

Here’s the board mounted in the lower tray portion of the case:

raspberry pi 13

And here’s the board with the middle section of the case attached:

raspberry pi 14

And here’s what the Pi looks like once the case is assembled:

raspberry pi 15

Assembling the case is pretty easy, as no tools are required. It simply snaps together.

Here’s the case on my desk, placed beside a $20 bill for size comparison:

raspberry pi 16

The Pi case is smaller than the hard drive that I connected to it (you can see it below the Pi):

raspberry pi 18

I decided to take the beginner route and start up the system using NOOBS, short for “New out of the box software”. It came pre-loaded onto the SD card that came with the board, and it installed Raspbian, the official supportedRaspberry Pi OS, and based on Debian. Once the OS is installed, here’s what you see when you boot up the Pi:

raspberry pi 19

Once it finishes booting up, you’re taken to a GNOME desktop:

raspberry pi 20

I used to have a stack of USB keyboards, but I’d given most of them away to friends and family, and my last couple are still back in Toronto. Figuring that I’d end up taking the Pi to meetups, BarCamps, and other demo sessions, or perhaps use it as a living room media center / internet device, I went with the Logitech K400 all-in-one keyboard, shown below. It’s currently on sale at Walmart for US$20:

raspberry pi 21

And thanks to Anastasia Sistevaris, an intern at Wiley, I got hooked up with a set of Raspberry Pi books, the first of which arrived recently: Exploring Raspberry Pi by Derek Molloy. I’ll do a writeup of this book in a later article:

raspberry pi 22

Watch this space for more Raspberry Pi articles as I start noodling with my new toy!

{ 0 comments }