date and time

swift kickSo far in this series, we’ve looked at:

So far, everything we’ve done has a distinctly un-Swift-like feel to it. That’s because Cocoa’s date and time classes were built with its original programming language, Objective-C, in mind. In this article, we’ll look at ways to make date calculations feel more “human” and Swift-like.

Make date comparisons more Swift-like

Let’s start with a new playground and some quick definitions:

  • A reference to the user’s calendar,
  • an NSDateFormatter and format string that makes it easy to define dates in a hurry,
  • and two dates:
    • Valentine’s Day (February 14, 2015 at midnight)
    • St. Patrick’s Day (March 17, 2015 at midnight)

Here’s what your code should look like:

In the previous article, we looked at NSDate's compare method, which compares two NSDates and returns a result of type NSComparisonResult as shown in the table below:

If… compare returns…
the first date is earlier than the second date .OrderedAscending
the first date is equal to the second date .OrderedSame
the first date is later than the second date .OrderedDescending

Add the following code to your playground:

The compare method works well, but its syntax has that C-style clunkiness. It’s a bit jarring in Swift, which has a lot of features that so-called “scripting” languages have. Wouldn’t it be nice if we could compare dates using the ==, <, and > operators?

Let’s make it happen. Add the following code to your playground:

With these functions, we’re simply overloading the ==, <, and > operators so that they work on NSDates and hide the clunky compare syntax behind some syntactic sugar. In case you’re wondering about the parameter names, lhs is short for “left-hand side” and rhs is short for “right-hand side”.

Note than in our overload of the == operator, there are a couple of ways that two dates can be considered equal:

  • Their compare result is NSComparisonResult.OrderedSame, or
  • the two dates being compared are the same NSDate object (=== is the identity operator; if a === b, then a and b both reference the same object).

Make date comparisons more “human”

picard data riker

One recurring theme in science fiction and especially in Star Trek is the tendency for ultra-smart characters and computers to be overly, needlessly, pointlessly precise. The writers for the original series often did this with Spock, and it seemed that at least a few writers were aware of this annoying trope in later series. Here’s a bit of dialogue from The Next Generation:

Data: 6 days, 13 hours, 47 minutes.
Riker: What, no seconds?
Data: I have discovered, sir, a certain level of impatience when I calculate a lengthy time interval to the nearest second. [beat] However if you wish…
Riker: No. No. Minutes is fine.

NSDate‘s compare method, and, by extension, the ==, <, and > overloads we defined, have the same problem with being overly precise. Let’s consider a case where we have two NSDates that are only a second apart:

  • Groundhog Day 2015 (February 2, 2015) at 12:00 a.m. EST
  • One second after Groundhog Day 2015 at 12:00 a.m. EST

For most purposes, we’d consider midnight on Groundhog Day and one second after midnight Groundhog Day the to be the same time. We need a way to do date comparisons at granularities other than seconds.

If you’re targeting iOS 8 or later, such a way already exists: NSCalendar‘s compareDate method! It expects the following parameters:

Parameter Description
fromDate The first date in the comparison.
toDate The other date in the comparison.
toUnitGranularity The level of precision for the comparison, expressed as an NSCalendarUnit value, which includes:

  • .SecondCalendarUnit
  • .MinuteCalendarUnit
  • .HourCalendarUnit
  • .DayCalendarUnit
  • .MonthCalendarUnit
  • .YearCalendarUnit

This is a Cocoa method with the word “compare” in its name, and you’ve probably guessed that its return type is NSComparisonResult. Here’s what it returns:

If… compareDate returns…
fromDate is earlier than toDate, when compared at the specified level of precision .OrderedAscending
fromDate is equal to toDate, when compared at the specified level of precision .OrderedSame
fromDate is later than toDate, when compared at the specified level of precision .OrderedDescending

Let’s try compareDate out:

Note that compareDate checks to see if the two given dates are in the same given time period. It doesn’t check to see if the two given dates are separated at most by the given time period. If you’re finding that distinction hard to follow, don’t worry; it’s hard to explain.

It’s easy to demonstrate, however. Suppose we create a new NSDate that represents one second before Groundhog Day and run some compareDate tests on it:

Note that compareDate isn’t available in iOS versions prior to 8. Code targeting iOS 7 or earlier will require writing an equivalent method, which I’ll leave as an exercise for the reader.

Making date arithmetic more Swift-like

You may have noticed in the code so far that I’ve been creating NSDates by using an instance of NSDateFormatter and a defined format string. That’s because this approach uses fewer lines than creating an NSDateComponents instance, setting its properties, then using a calendar to use the NSDateComponents instance to create an NSDate. Unfortunately, there’s no built-in quick way to build an NSDateComponents instance that represents an interval of time.

This means that answering questions like “What will the date be 1 month, 8 days, 6 hours, and 17 minutes after Groundhog Day?” requires a lot of yak shaving, my favorite term for “tedious setting-up”:

This approach is a clunky Objective-C-flavored way of doing things. I’d much rather do this calculation with code that looked like this:

Luckily, we’re working with Swift. Some judicious use of operator overloading and extensions will let us do just that!

First, we need to overload some operators to simplify date component arithmetic:

I derived these functions from Axel Schlueter’s SwiftDateTimeExtensions library. He wrote them when Swift was still in beta; I updated them so that they compile with the current version and added a couple of tweaks of my own. They make it possible to:

  • Add the respective second, minute, hour, day, month, and year properties of two NSDateComponent instances,
  • subtract the second, minute, hour, day, month, and year properties of one NSDateComponents instance from the corresponding properties of another NSDateComponents instance, and
  • negate the second, minute, hour, day, month, and year properties of an NSDateComponents instance.

The addition and subtraction operations are so similar and so tedious; that’s a sign that there’s an opportunity to DRY up the code. That’s why we have the combineComponents method doing the work and the + and - overloads calling it with the right parameters. The combineComponents code is dense with ternary conditional operators, so I thought I’d explain what’s going on under the hood with this flowchart:

combineComponents

You may be wondering why we defined a negation method and didn’t use it when performing subtraction. That’s because the negation method simply ignores undefined components, while addition and subtraction require treating undefined component values as 0. The negation method comes in handy in other scenarios, which I’ll show later.

Now that we’ve got date component addition, subtraction, and negation defined, let’s extend the Int type so that it has some instance properties that let us define components with statements like 5.seconds, 3.minutes, 7.hours, 2.days, 4.weeks, and so on:

Once again, I derived these functions from Axel Schlueter’s SwiftDateTimeExtensions library and added a couple of tweaks of my own.

There’s a little redundancy in the code above; it’s to allow for grammatically correct code. I didn’t like seeing code like 1.seconds, 1.minutes, 1.hours, 1.days, and so on.

With the date component addition and subtraction overloads and the extension to Int, building date components that represent time intervals is far less tedious:

With all our tweaks, adding components to dates using NSCalendar‘s dateByAddingComponents feels clunky by comparison. Here are some operator overloads that make this sort of coding more elegant if you’re working with dates and date components expressed in terms of the user’s current calendar:

With these methods, date arithmetic now looks like this:

That code is so much more pleasant to read (and write!).

And finally, a Ruby on Rails trick comes to Swift

Ruby on Rails lets you do very readable calculations like 2.days.from_now and 2.days.ago. We can bring that Rails magic to Swift by using everything we’ve build so far and extending NSDateComponents with two computer properties:

Equipped with everything we’ve made, we can now write code like this:

The entire playground

And with that. we’ve got a more Swift-like way of doing date arithmetic. I’m going to take all these methods and extensions and post them as a library on GitHub, but in the meantime, here’s the complete playground for the exercises in this article. Go forth and write some readable date/time code!

{ 2 comments }

delete my browser history shirt 2

You’d think that a wizard would know about “Privacy Mode” (which I sometimes refer to as “porn mode”), but I suppose one doesn’t pick up that sort of thing when one is on a mission to save Middle Earth.

This T-shirt is available right now for $15 plus free shipping at Woot!

How to delete your wizard friend’s (yeah, right) browser history

delete my browser history shirt

Should a wizard ever ask you to do him this favor, here’s how you do it. The instructions for Chrome, Firefox, and IE come straight from Woot!’s page for the T-shirt, and the instructions for Safari on Mac OS come from Yours Truly.

Instructions for Chrome:

  1. Open your browser
  2. Click the Chrome button in the top-right of the browser window
  3. Select History
  4. Click the Clear browsing data button
  5. From the drop down, select the duration of time you want to delete from your history. To delete all history, select the beginning of time
  6. Check the boxes of the data you would like to delete, including Browsing history and Download history
  7. Click the Clear browsing data button
  8. Slay balrog

For Mozilla Firefox:

  1. Open your browser
  2. Click the menu button in the top-right of the browser window
  3. Select History, then Clear Recent History
  4. Select the time range to clear. To clear all browser history, select Everything
  5. Click Clear Now
  6. Return to Middle Earth as angelic white wizard

For Internet Explorer:

  1. Open your browser
  2. Click the Tools button in the top-right of the browser window
  3. Select Safety, then Delete Browsing History
  4. Check the boxes of the data you would like to delete, including Temporary Internet files and website files, History and Download History
  5. Un-check Preserve favorite website data
  6. Click Delete
  7. Ride forth upon Shadowfax and lead the Rohirrim to victory at Hornburg

For Safari (on Mac OS)

  1. Open your browser
  2. Select Clear History… from the History menu
  3. Click Clear when the Are you sure you want to clear history? dialog appears
  4. Open Preferences by either selecting Preferences… from the Safari menu or typing ⌘, (the “command” and “,” keys simultaneously)
  5. Select the Privacy tab and click Remove all website data…
  6. Click Remove Now when the Are you sure you want to remove all data stored by websites on your computer? dialog appears
  7. Evade the omnipresent glance of the Eye of Sauron

{ 0 comments }

how the internet turned out

{ 3 comments }

cocoa date time class chart

Click the chart to see it at full size.

swift kickIn the previous installment in this series that looks at working with dates and times in Cocoa, we looked at:

  • The NSDate class, which is the heart of date and time in Cocoa, and represents a single point in time relative to the start of the third millennium (midnight, January 1, 2001)
  • the NSCalendar class, which provides a context for dates and the ability to do date arithmetic,
  • the NSDateComponents class, which represents the parts that make up either a date or a span of time, and
  • the NSDateFormatter class, which turns dates into string representations and vice versa.

We also covered creating dates, converting components into dates and vice versa, and converting dates into strings and vice versa. With this knowledge under our belts, let’s get to this article’s topic: doing date calculations.

Creating a couple of dates to work with

valentines st patricks

Start with a fresh playground, and enter or paste the following code so it looks like this:

In the code above, we’re creating two dates in two different ways (which we covered in the previous article):

  • We’re creating Valentine’s Day (February 14 for those of you in places where it’s not celebrated) by setting up date components and then using the user’s calendar to convert the components into a date.
  • We’re creating St. Patrick’s Day (March 17 for those of you in places where it’s not celebrated) by converting a string representing that date into a date by means of a date formatter. You may find that if you need to instantiate a large number of dates in code, you may want to do so this way, as you can do it in far fewer lines than by using date components.

Now that we have a couple of date objects, let’s do some date arithmetic!

Which came first?

which came first

NSDate has two methods, earlierDate and laterDate, which compare one date to another and return the appropriate date. Add the highlighted code below so that your playground looks like this:

This is pretty straightforward: valentinesDay.earlierDate(stPatricksDay) returns the valentinesDay instance, while valentinesDay.laterDate(stPatricksDay) returns stPatricksDay.

NSDate has a compare method that works in a way similar to a lot of other “compare” methods (such as C’s strcmp) that compare a value a and b, where:

  • If a < b, it returns a negative number
  • if a == b, it returns 0
  • if a > b, it returns a positive number

Cocoa comparison methods return values of type NSComparisonResult, so that when you’re comparing two values a and b:

  • If a < b, it returns NSOrderedAscending
  • if a == b, it returns NSOrderedSame
  • if a > b, it returns NSOrderedDescending

Let’s take it out for a spin. Add the highlighted code below so that your playground looks like this:

Valentine’s Day comes before St. Patrick’s Day, so the result you see the in sidebar should be Valentine’s Day comes before St. Patrick’s Day.

Date arithmetic: How far apart are two dates and times?

countdown clock

NSDate has the timeIntervalSinceDate method, which gives you the difference between 2 dates…in seconds.

Since Valentine’s Day comes before St. Patrick’s Day, the first value is negative, while the second value is positive. Most users won’t find knowing that there are nearly 2.7 million seconds between the two days. How can we find out the number of days between Valentine’s and St. Patrick’s?

That’s where date components come in. I mentioned last time that date components can represent either:

  • A specific point in time, or
  • a duration of time.

We’re going to use date components for the second purpose in this example. We need to do the following:

  • Specify the units of time that we want from the calculation, which in this case is days, and
  • Provide those units of time and the two dates to NSCalendar‘s components method:

This version of NSCalendar‘s components method takes the following arguments:

  • unitFlags: a bitwise OR of NSCalendarUnit constants, which specify the units of the result. Since we want to know the number of days between Valentine’s and St. Patrick’s, we set this to the value NSCalendarUnit.DayCalendarUnit.
  • fromDate: The start date in the calculation.
  • toDate: The end date in the calculation.
  • options: In most cases, you’ll want this set to nil, which causes overflows in a unit to carry to the next higher unit. For example, if you specify in unitFlags that you want your result expressed in minutes and seconds, and the calculation’s result is 61 seconds, the result will be changed to 1 minute, 1 second.

Let’s try another calculation: what’s the time difference between 10:45 a.m. and 12:00 noon?

You should see in the sidebar that timeDifference.hour‘s value is 1 and timeDifference.minute‘s value is 15.

Date addition and subtraction

plus minus dice

If you’re writing some kind of reminder app, you might want to be able to let the user say “give me a reminder in 10 days”, which means you’ll need to calculate what the date and time will be 10 days from now. Since we’re doing date addition with only one unit, we can perform this calculation by using NSCalendar‘s dateByAddingUnit method:

dateByAddingUnit expects the following parameters:

  • unit: The type of unit to be added to the date. We want to add days, so we’re setting this value to NSCalendarUnit.DayCalendarUnit.
  • value: The number of units to be added to the date. We want to know what the date will be 10 days from now, so we set this to 10.
  • toDate: The date to which we’ll be adding units. We want to add 10 days to today, so we set this to a new NSDate (remember, instantiating an NSDate object without parameters creates an instance that refers to the current date and time).
  • options: In most cases, you’ll want to set this to nil.

I ran the code on January 28, 2015 at 11:29 p.m., so the resulting date stored in tenDaysFromNow is displayed in my playground’s sidebar as Feb 7, 2015, 11:29 PM.

I wanted to know what day of the week it would be 10 days from now, and which weekday of the month (the first, second, third…?) so I used the version of NSCalendar‘s components method that takes a single date and use it to extract the weekday and weekdayOrdinal components from tenDaysFromNow. At the time I ran the code, tenDaysFromNowComponents.weekday‘s value was 7 (Saturday) and tenDaysFromNowComponents.weekdayOrdinal‘s value was 1 (meaning that it’s the first Saturday of the month).

Here’s another calculation: what was the date and time 3 days, 10 hours, 42 minutes, and 5 seconds ago? We’re doing date arithmetic with more than one kind of unit — days, hours, minutes, and seconds — so we need NSCalendar‘s dateByAddingComponents method instead:

dateByAddingComponents expects the following parameters:

  • comps: the date components that we want to add to the given date. Note that since we’re performing date subtraction, all the components are expressed as negative numbers.
  • toDate: The date from which we’ll be adding (or in this case, subtracting). We want to subtract from the current date and time, so we set this to a new NSDate object instantiated without parameters (which, as I’ve said before, gives an instance representing the current date and time).
  • options: In most cases, you’ll want to set this to nil.

I ran the code on January 28, 2015 at 11:52 p.m., so the resulting date stored in then is displayed in my playground’s sidebar as Jan 25, 2015, 1:10 PM.

In closing

In this article, we covered:

  • Comparing two dates to see which one is the earlier on and which is the later one,
  • finding out how far apart two dates are, and
  • adding and subtracting from dates.

In the next installment, we’ll a closer look at date calculations and see some convenience methods that make date and time calculations simpler.

{ 1 comment }

Apple’s astonishing quarter

the most profitable quarter ever
Yesterday, which also happened to be the fifth anniversary of Steve Jobs’ iPad announcement…

Apple posted the financial results for their fiscal first quarter of 2015, in which they made a net profit of $18 billion. That’s not just a record for Apple, but for any company, any time in human history. The previous record-holder was the Russian firm Gazprom, the world’s largest extractor of natural gas.

The insanely popular iPhone 6 and 6 Plus carried the company, who sold nearly 75 million iPhones (in previous quarters, they had yet to surpass the 60 million mark, never mind 70 million), a 46% increase from the same quarter in the preceding year. “Greater China” — Apple’s term for the area comprising mainland China, Hong Kong, and Taiwan — helped push Apple over the top. They accounted for $16 billion of the nearly $75 billion revenue for Q1 2015.

This success in China comes at a cost to Samsung, whose market share in the Middle Kingdom is dropping. There’s a good summary of this situation in Bloomberg Business’ article, Apple Learns What Samsung Forgot: How to Sell Phones in China.

If there’s a cloud in all this silver lining, it’s iPad sales, which dropped to 21.4 million, a decrease of 21% year over year. In Wired’s article, How the iPad Went From Massive to ‘Meh’ in 5 Short Years, it’s noted that the iPad lives in that zone between smartphone and laptop, a gap that’s being closed by larger phones and thinner, lighter laptops.

Samsung: Speaking of earnings reports…

samsung q4 2014 report
Samsung will release its 4Q 2014 earnings report on Thursday morning in Seoul (in the UTC+0900 time zone, 14 hours ahead of North America’s Eastern Time), before markets open. According to the Wall Street Journal, here’s what we should expect:

  • Net profit: 4.5 trillion won ($4.2 billion)
  • Revenue: 52 trillion won ($48.3 billion)
  • Mobile: operating profit down 65% from the same time during the previous year, shipped 10 million fewer units as well
  • Chips: a 40% rise in profit, and increased production of mobile processors for both their devices and Apple’s

BlackBerry’s modest proposal

blackberry free market
In a recent post on BlackBerry’s blog, CEO John Chen talks about net neutrality and carrier neutrality, and what he says sounds sane and sensible. He then follows with application/content neutrality, and that’s where things get a little weird:

Unlike BlackBerry, which allows iPhone users to download and use our BBM service, Apple does not allow BlackBerry or Android users to download Apple’s iMessage messaging service. Netflix, which has forcefully advocated for carrier neutrality, has discriminated against BlackBerry customers by refusing to make its streaming movie service available to them. Many other applications providers similarly offer service only to iPhone and Android users. This dynamic has created a two-tiered wireless broadband ecosystem, in which iPhone and Android users are able to access far more content and applications than customers using devices running other operating systems. These are precisely the sort of discriminatory practices that neutrality advocates have criticized at the carrier level.

Therefore, neutrality must be mandated at the application and content layer if we truly want a free, open and non-discriminatory internet. All wireless broadband customers must have the ability to access any lawful applications and content they choose, and applications/content providers must be prohibited from discriminating based on the customer’s mobile operating system.

In other words, “Developers and online services like Netflix should be mandated by law to build BlackBerry apps,” apparently forgetting that in better BlackBerry-dominated times, BBM was a BlackBerry-only service and a competitive advantage.

PC World’s Jared Newman does a great job of explaining why Chen is wrong when it comes to “app neutrality”:

On some level, Chen’s position is understandable. The point of net neutrality is to encourage innovation in online services, and to prevent Internet providers from picking winners and losers. Chen is saying that BlackBerry hasn’t been given a fair shot because app makers have declared iOS and Android victorious.

But there’s a critical difference between net neutrality and the app neutrality that Chen proposes: With net neutrality, non-discrimination is the default. The Internet stops being neutral only if Internet providers create new, discriminatory practices such as blocking, throttling and fast lanes. The point of net neutrality rules is to maintain the Internet in its non-discriminatory state.

With Chen’s proposal of app neutrality, no such non-discriminatory state exists. Each new platform merely creates more work for developers, thereby requiring greater investment. Under Chen’s proposal, the barriers to entry for a small startup would become greater, and innovation would be stifled. App neutrality may be beneficial for BlackBerry, but it would actually counteract the things that net neutrality is trying to achieve.

Our guess is that Chen added “app neutrality” to his article on net neutrality as a way to attract more attention to it, generate discussion, and keep BlackBerry on people’s minds. Well played, sir.

At least it’s not as bad as tweeting BlackBerry promotional messages from an iPhone…

this article also appears in the GSG blog

{ 0 comments }

How to work with dates and times in Swift, part one

by Joey deVilla on January 26, 2015

i just want to use dates

swift kickIf you’re just getting started with date and time programming in Swift, chances are that you probably did some Googling, found NSDate and its companion classes in Apple’s documentation and promptly got confused. Let me reassure you that it isn’t your fault. Apple’s Date and Time Programming Guide isn’t set up in the most helpful way, and its examples are in Objective-C, which can throw you off if you’re not familiar with its [instance method] calling syntax.

If you’re coming to Swift 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:

cocoa date time class chart

Click the chart to see it at full size.

This is the first article in a short series on programming dates and times in Swift. It’ll help you make sense of working with NSDate and its companion classes.

What is UTC? (or: “It’s 5 o’clock somewhere!”)

what time is it right now

People who like to drink are fond of saying “Well, it’s five o’clock somewhere!“, and it’s my favorite way of illustrating that what time it is depends on where you are. It’s why we have UTC — Coordinated Universal Time — the “One True Time” on which every other time zone is based. UTC replaced GMT (Greenwich Meridian Time, the time as observed at the Royal Observatory in Greenwich, London), and it doesn’t change for daylight savings. By having this standard, we eliminate the confusion that comes up when discussing times.

While most places have some names to refer to time zones in everyday conversation — such as Pacific, Mountain, Central, and Eastern in North America — the clearest way to indicate time zones is to express them as negative or positive offsets from UTC. For example, the North American time zone known as “Eastern” is 5 hours behind UTC, so it’s expressed as UTC-05:00. There are certain time zones where the offset isn’t whole hours, such as Newfoundland’s, which is UTC-03:30, and Nepal’s, which for some reason is UTC+05:45.

NSDate: Cocoa standard time

When you want to represent a date or time in Cocoa, you do so with an instance of the NSDate class. Here’s a nice, simple description of what NSDate is:

nsdate

When you’re measuring time, you need a reference point. The Gregorian calendar — the one that I’m 99.999999% sure that you’re using right now — uses what is said to be the year of the birth of Christ as its reference point. Your age uses the date of your birth as a reference point. A time trial race uses the time at the start of the race as its reference point.

NSDate‘s reference point is the start of the third millennium: January 1, 2001 at midnight UTC. It stores time as an NSTimeInterval, a 64-bit floating point value representing a number of seconds. Negative values represent a number seconds before January 1, 2001, 00:00 UTC, and positive values represent a number seconds after that time. According to Apple’s documentation, this representation of time “yields sub-millisecond precision over a range of 10,000 years”, which means that an NSDate instance can represent any point in time from about 3000 BC/BCE to 7000 AD/CE.

Here are 4 historical dates, as seen from NSDate‘s perspective:

historical dates nsdate style

There are some consequences to the fact that NSDate treats time as an offset of seconds:

  • All NSDate values refer to both a date and a time. If you want to use an NSDate to store a date only, you ignore the time portion, and vice versa.
  • NSDate has no concept of time zones or any time unit other than seconds. That means you can’t ask it what year, month, day, hour, or minute correspond to the time it’s storing. As far as it’s concerned, there are no calendars; you work with NSDate‘s representation of time, when it’s time to display a date, time, or both, you format it to use the calendar and time zone that’s appropriate for the user.

There’s a method to this madness: it allows us to use and store dates and times in a way that’s independent of calendar systems, time zones, languages, and date formats. As I write this, it’s the year 2015 in the Gregorian calendar, but the Buddhist calendar says it’s 2558, and if you go by the Hebrew Calendar, it’s 5775. I may say it’s 9:45 a.m. as I write this in Tampa, but if you’re in California, it’s 6:45, and if you’re a soldier, you might call it 14:45 Zulu Time. I call the current month January, but you might call it Enero or Janvier. It’s all the same as far as NSDate is concerned, which makes it incredibly flexible.

Creating NSDates without any helper classes: now is easy, other dates ain’t so pretty

Let’s create some NSDates right now. Fire up Xcode, open a new playground, and enter the following code so that it looks like this:

You should see results in the sidebar that look similar to this:

playground 1

If you create an NSDate without any parameters, you get an instance representing the date and time at the moment it was created. That’s what we’ve done by creating the instance named now.

Note that in the sidebar beside line 5, where we created now, the result displayed in the sidebar is Jan 19, 2015, 8:52 AM. While the internal representation of the current time is a 64-bit floating point value, Xcode’s doing us a favor by representing it in a more readable format and using the local time zone. It’s doing this by making use of a date formatter, which we’ll cover later.

In line 6, we’re using the println function to display the default string representation of an NSDate, which is a completely numeric one. It’s more readable than a 64-bit floating point value, but it might not be in the format or time zone (or even the calendar system) that you want. Once again, this output comes courtesy of a date formatter.

Finally, in line 7, we use the timeIntervalSinceReferenceDate property to display now‘s internal representation of the date and time it’s storing: about 443 million seconds after January 1, 2001 at midnight UTC.

Let’s create the dates from the Historical dates, NSDate style picture above. Enter or paste the highlighted code below so that your playground looks like this:

In the sidebar, you should see nicely-formatted dates beside the NSDates you created.

NSDate has four initializers for creating specified dates and times:

Initializer Description
init(timeIntervalSinceReferenceDate:) Create an NSDate instance representing a time specified by a number of seconds before or after January 1, 2001 00:00 UTC.
init(timeIntervalSinceNow:) Create an NSDate instance representing a time specified by a number of seconds before or after the current date and time.
init(timeIntervalSince1970:) Create an NSDate instance representing a time specified by a number of seconds before or after January 1, 1970 00:00 UTC. This method exists not because Apple’s founders were California hippies nostalgic for the era of their youth, but for compatibility with Unix time.
init(timeInterval:sinceDate:) Create an NSDate instance representing a time specified by a number of seconds before or after a given NSDate.

You’ve probably noticed that none of these initializers lets you create an NSDate by giving it something convenient like a year, month, day, time zone and so on. Luckily, there are classes that will help us do this.

Creating NSDates with the help of NSCalendar and NSDateComponents

If you’re like most people, you’d probably much rather initialize a date object using a day, month, year, and time instead of some number of seconds before and after midnight on January 1, 1970, January 1, 2001, or any other arbitrary date. For this, we’ll need a couple of additional classes:

nscalendar and nsdatecomponents

First, there’s the NSCalendar class, which among other things, gives us a context for converting NSDate‘s “seconds before or after the third millennium” measurements into a familiar time system with years, months, days, hours, and minutes, and it accounts for time zones as well. Most of the time, the date and time system will be the Gregorian calendar, but iOS also lets you choose from 15 other calendar systems, including Hebrew and Buddhist.

Next, there’s the NSDateComponents class, which is an assembly of properties that make up a date, such as year, month, date, hour, minute, second, and so on. An NSDateComponents instance can be used to represent either:

  • A specific point in time, or
  • a duration of time.

To create an NSDate by specifying things like a year, month, day, and time, we’ll do the following:

  • Create an NSCalendar instance pointing to the user’s calendar
  • Specify a date using an NSDateComponents instance
  • Create the NSDate by passing the NSDateComponents instance to NSCalendar‘s dateFromComponents instance method

nsdatecomponents to nsdate

Let’s go back to our playground and create our first historical date: that of Alexander Graham Bell’s first phone call. We know it took place on March 10, 1876. While we don’t know the exact time it happened, we do know that it happened in North America’s Eastern time zone, as opposed to something like Kiritimati, a.k.a. Christmas Island. That place is 19 hours ahead and would’ve resulted in historians recording that day as March 11th rather than the 10th.

Enter or paste the highlighted code below so that your playground looks like this:

Any calendar, regardless of its time zone, to turn date components into dates using its calendar system. If you specify a time zone in the date components, it will take that time zone into account; if you don’t specify one, the date will be created using the calendar’s time zone. We created an instance of the user’s calendar, which incorporates the user’s local and time zone settings, because it’ll be useful later when we want to go in the opposite direction and convert dates into date components.

Note that after setting the year, month, and day properties of firstLandPhoneCallComponents, we set the timeZone component using the preferred initializer, init(name:), which lets you specify a time zone by any of the standard string identifiers listed in the tz database of time zones. I could’ve used one of the city names such as America/New_York (or for those of you familiar with Canada, America/Toronto, America/MontrealAmerica/Atikokan, or America/Pangnirtung) to specify the Eastern time zone. It’s far clearer — especially to people not from the U.S. — to use the time zone names that begin with US or Canada, such as US/Eastern, US/Central, US/Mountain, and US/Pacific rather than city names.

Once we’ve set up the date components, we use the calendar’s dateFromComponents instance method to convert them into a date. I’m in the US/Eastern time zone, the same one as the one specified in the date components, so the result in the sidebar beside this line of code shows as “Mar 10, 1876, 12:00 AM” (we didn’t specify a time in the date components, so the resulting date has the default time of 00:00). The date displayed in the sidebar uses your system settings, which may be different from mine.

Let’s enter the other three historic dates. Enter or paste the highlighted code below so that your playground looks like this:

Note that we used different time zones for the “Stevenotes”. Both took place at the same time, 10:00 a.m. Pacific, but we set the time for the iPhone announcement as 1:00 p.m. US/Eastern, and the time for the iPad announcement as 10:00 a.m. US/Pacific. Both results in the sidebar appear at the same time; on my machine, they appear as Jan 27, 2010, 1:00 PM.

dateFromComponents works with what you give it

Suppose we want to create a date just by specifying that it’s 11:00 a.m. on the first Saturday of March 2015 in the US/Eastern time zone. Here’s how it’s done:

NSDateComponentsweekday property lets you specify a weekday numerically. In Cocoa’s Gregorian calendar, the first day is Sunday, and is represented by the value 1. Monday is represented by 2, Tuesday is represented by 3, all the way to Saturday, which is represented by 7.

The weekdayOrdinal property lets you specify which specified weekday of the month. By setting weekday to 7, we’re specifying a Saturday; by then setting weekdayOrdinal to 1, we’re specifying the first Saturday of the month.

Here’s another example, where we get the date for the Thursday on the 18th week of 2015:

The other way around: getting NSDateComponents from NSDates

Right now, your playground should look like this, with a number of dates being created from date components:

Now it’s time to go the other way around, and extract date components from those dates. Once again, it’s the calendar that provides the method for making the conversion.

To extract NSDateComponents from an NSDate, we’ll do the following:

  • Create NSCalendar instances, if needed
  • Specify a set of date components using NSCalendarUnit bitmasks
  • Create the NSDateComponents by passing the NSDate instance to NSCalendar‘s components instance method

nsdate to nsdatecomponents

We already have a calendar instance: userCalendar, which is associated with the user’s time zone. If we use it to extract date components from a given date, the dates and times will be interpreted in the context of its time zone.

Let’s create two more calendars with two different time zones:

  • The US/Pacific time zone (UTC-08:00)
  • The Japan time zone (UTC+09:00)

Here’s what the code looks like:

Extracting all the possible date components from a date can be computationally costly, so NSCalendar‘s components instance method requires you to build a bitmask specifying the components you want to extract by ORing together NSCalendarUnit values. We want to extract these components from our dates:

  • year
  • month
  • day
  • hour
  • minute
  • weekday
  • weekdayOrdinal

Here’s the code:

Now that we’ve done that, we can start extracting date components:

In your playground’s sidebar, you should see results similar to those listed in the table below:

Component My user calendar Pacific calendar Japan calendar
year 2007 2007 2007
month 1 1 1
day 9 9 10
hour 13 10 3
minute 0 0 0
weekday 3 3 4
weekdayOrdinal 2 2 2

As you can see, January 9, 2007 at 10:00 a.m. in the US/Pacific time zone is January 9, 2007 at 1:00 p.m. in my time zone (US/Eastern) and January 10, 2007 at 3:00 a.m. in Japan. In the US, that date was the second Tuesday in January 2007; in Japan, it was the second Wednesday.

Turning dates into strings (and vice versa) with NSDateFormatter

nsdate - nsdateformatter - stringJust as you use an calendar to convert date components into dates and vice versa, you use a date formatter — an instance of the NSDateFormatter — to do the conversions.

Formatting date strings for the user

If you need to display a date as text for the user, it’s best if you use Cocoa’s built-in date styles. These are a set of predefined styles for formatting dates and times based on the user’s preferred settings. These styles, which are all values of the NSDateFormatterStyle enumeration, come in a selection of lengths — short, medium, long, and full — and using them is the preferred way to create date strings for the user to read.

Add the following code to your playground:

Here’s how the various date and time formatter styles get rendered:

If dateStyle and timeStyle are both set to… the date formatter’s output looks like…
NoStyle
ShortStyle 1/27/10, 1:00 PM
MediumStyle Jan 27, 2010, 1:00:00 PM
LongStyle January 27, 2010 at 1:00:00 PM EST
FullStyle Wednesday, January 27, 2010 at 1:00:00 PM Eastern Standard Time

What’s up with NoStyle? It’s there so you can limit the resulting string so that it shows only the date or only the time.

NSDateFormatter has a timeZone property so that you can ensure that the date string reflects a specific time zone:

Formatting date strings for other computers

As I wrote earlier, if you’re formatting dates for the user, it’s strongly recommended that you use NSDateFormatter‘s dateStyle and timeStyle properties, which will format dates and times according to the user’s settings. However, if you need to need your date strings to be in a specific format (for an API, for example), you can provide NSDateFormatter with a format string:

While you can browse through Appendix F of the Unicode Technical Standard #35 to look at all the date format specifiers supported by NSDateFormatter, you might find it easier to use the table below. It shows a number of format strings applied to the iPhone announcement date (January 9, 2007 at 10:00 a.m. Pacific):

Format string Result
'Year: 'y' Month: 'M' Day: 'd Year: 2007 Month: 1 Day: 9
MM/dd/yy 01/09/07
MMM dd, yyyy Jan 09, 2007
E MMM dd, yyyy Tue Jan 09, 2007
EEEE, MMMM dd, yyyy' at 'h:mm a. Tuesday, January 09, 2007 at 10:00 AM.
EEEE, MMMM dd, yyyy' at 'h:mm a zzzz. Tuesday, January 09, 2007 at 10:00 AM Pacific Standard Time.

Turning strings into dates

If you specify a date format string, you can use NSDateFormatter to take a string following that format to turn it into an NSDate. For example:

Tying it all together

If you’ve made it to this point in the article, this chart should now make sense:

cocoa date time class chart

Once again, click the chart to see it at full size.

You should now be able to:

  • Create dates “from scratch” (that is, create them using an offset of a number of  seconds from the start of the third millennium)
  • Create dates from date components (that is, from numbers representing a day, month, and year)
  • Convert between dates and date components
  • Convert dates into string representations and string representations of dates into dates

In the next article in this series, we’ll look at date calculations and some handy functions that let you harness Swift’s expressive power and make working with dates easier.

{ 4 comments }

If someone walked up to you on the street and asked you what your password was, would you say?

The TV show Jimmy Kimmel Live sent an interviewer out on the street to ask (presumably) random people on Hollywood Boulevard what their passwords were. As you might expect, they showed only those people who gave away their passwords (and of that group, only those who signed a release form to appear on the show), but the fact that anyone did so shows that we’ve got a big security problem, and it’s us. A couple of them simply gave them away without question, while a couple of others has to be conned — very easily — into divulging.

This is the technologist’s nightmare. For all the security measures we put into our applications and devices, they can easily be undone by the users. That’s why I often make use of this cartoon when talking about security:

and in this corner we have dave

The article also appears in my personal blog, The Adventures of Accordion Guy in the 21st Century.

{ 2 comments }