Working with Dates in Swift

Working with Dates in Swift

To start working with dates in iOS you must be familiar with at least these three objects: Date, DateFormatter and DateComponents.

Date struct

Date is a struct that belongs to the Foundation framework.

It represents a specific point in time independent of any calendar or time zone.

Date structure bridges to the NSDate class.

It provides methods for creating dates, comparing dates and calculating time intervals between dates.

It DOES NOT do anything related to date format or conversion between string and date.

DateFormatter class

Belongs to the Foundation framework

A formatter providing methods for converting from Date to String and from String to Date.

It also allows you to customize the representation of the date string using predefines styles or building your own format.

It also supports localization.

DateComponents struct

Belongs to the Foundation framework.

This is a Date or Time object represented in units such as year, month, day, minute or hour in a particular calendar.

It provides direct access to different parts of date or time.

Now lets write some code to demonstrate how to work with dates in Swift.

Creating Date in Swift using Date()

Create a date with current date and time

let currentDate = Date()

//Saturday, November 25, 2017

Create a date by adding time interval-in seconds- to current date

let date = Date.init(timeIntervalSinceNow: 86400)

//Sunday, November 26, 2017

Create a date by adding time interval – in seconds – since reference date

let date = Date.init(timeIntervalSinceReferenceDate: 86400)

//Tuesday, January 2, 2001

please note that reference date is 00:00:00 UTC on 1 January 2001.

Converting Date to String using DateFormatter

let dateFormatter = DateFormatter()

dateFormatter.dateStyle = .full

dateFormatter.timeStyle = .full

let dateString = dateFormatter.string(from: date)

Result:

Saturday, November 25, 2017 at 8:22:04 PM GMT

First we create an instance of DateFormatter

Next we choose a style for the date from 5 predefines styles (none, full, long, short, medium), select none to hide the date part.

Then choose a style for the time from 5 predefined styles (none, full, long, short, medium), select none to hide the time part.

Finally we use DateFormatter to get string representation of our date

If you do not want to use one of the predefines styles you can create your own using dateFormat property

dateFormatter.dateFormat = "MMMM-dd-yyyy HH:mm"

//November-25-2017 22:04

MMMM: full month name

dd: day

yyyy:year

HH: hours in 24 format

mm: minutes

You can get a complete list of date format patterns here

Converting String to Date using DateFormatter

The dateFormat property of the DateFormatter MUST match the date format of the string.

let dateString = "25/01/2011"

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "dd/MM/yyyy"

let dateFromString = dateFormatter.date(from: dateString)

Comparing Dates

Date() conforms to Comparable protocol so you can simply use < , > and == to compare two dates.

if leftDate < rightDate { 
       print("leftDate is earlier than rightDate") 
} else if leftDate > rightDate {
       print("leftDate is later than rightDate")
} else if leftDate == rightDate {
       print("dates are equal")
}

Create DateComponents from Date

First of all you need to set your calendar then use it to create components

let dateCurrent = Date()

let calendar = Calendar.current

let components = calendar.dateComponents([Calendar.Component.day, Calendar.Component.month, Calendar.Component.year], from: dateCurrent)

print("Day:\(components.day!) Month:\(components.month!) Year:\(components.year!)")

Result

Day:27 Month:11 Year:2017

Create Date form DateComponents

let calendar = Calendar.current

var components = DateComponents()

components.day = 25
components.month = 1
components.year = 2011
components.hour = 2
components.minute = 15

let newDate = calendar.date(from: components)

print(newDate!)

Result

2011-01-25 02:15:00 +0000

Finally those was just few examples of what you can do with Date, DateFormatter and DateComponents.

Please tell me if you have any comments, questions or suggestions.

You might like Working with CALayer tutorial

 

Leave a Reply

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