Subjects

Topics

In Bite # 286 we looked at the basic use of DateFormatter s to transform Date s to String p.

I Today we will explore another common mode of use at Date Say Our Apps: "Relative" Data Strings .

Think "2 days ago" "10 minutes ago" "Yesterday" and "Just now" . It represents time stamps in this way has become commonplace and it can help our users understand how old a content is.

Let's add this functionality to our app by expanding Date to give it a new estimated property to do this.

We start by adding a new file to our Xcode Project . We call it Date + Relative.swift . Type + SomeExtensionName The convention is borrowed from Objective-C .

Then we will set up our extension :

extension ] {1

9659015] was relativeFormatted : String { // TODO } }

Nice. Needs a way to calculate how much time it is between now and even (from the extended Date s point of view.) We could make a bunch of ugly maths, but we have a better way!

This is an amazing mode of use for the Foundation's DateComponents type. It has a function that can calculate the difference between two Date s and give it to us in a nicely (pre-calculated ) components like days, months, hours, seconds, etc.