Date with Swift

57 seconds

Date objects represent a single point in time. It is independent of any particular calendrical system or time zone.

Date is an abstract class that provides behavior for creating dates, comparing dates, representing dates, computing intervals, and similar functionality.

Date presents a programmatic interface through which suitable date objects are requested and returned.


let date = Date()

This will generate a timestamp at the time code is executed.

Local Time to UTC

Date generated is actually know what is the time zone for the local time.

We will use DateFormatter to change the way it will present to users with specific formating.

DateFormatter can change attibute like dateFormat, and timeZone.


let date = Date();
// "Nov 2, 2016, 4:48 AM" <-- local time

var formatter = DateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ";
let defaultTimeZoneStr = formatter.string(from: date);
// "2016-11-02 04:48:53 +0800" <-- same date, local with seconds and time zone
formatter.timeZone = TimeZone(abbreviation: "UTC");
let utcTimeZoneStr = formatter.string(from: date);
// "2016-11-01 20:48:53 +0000" <-- same date, now in UTC

DateFormatter

Instances of NSDateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

Date Format Patterns

Online NSDateFormatter

Locale

For real usage with formatter we have to set the locale outright to "en_US_POSIX" to make it standardize to read or write the date between String and Date. It is because users worldwide has different locale.

It might be a chaos if some user use Arabic, it will display like: "٠٠٠١-٠١-٠٢ ٠١:٤٣:١٤ +0000". Use "en_US_POSIX" to enforce everyone will use this standard computer format.


let date = Date();
var formatter = DateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ EEEE";
formatter.locale = Locale(identifier: "en_US_POSIX")
var dateString = formatter.string(from: date)

List of Locales

However you may honour user's locale by displaying date in specific locale style. For example 'EEEE' date format refer to name of day in specified locale.


let date = Date();
var formatter = DateFormatter();
formatter.locale = Locale(identifier: "en_US")
//formatter.locale = Locale(identifier: "en_US_POSIX")
//formatter.locale = Locale(identifier: "ja_JP")
//formatter.locale = Locale(identifier: "ms")
formatter.dateFormat = "EEEE";
var dateString = formatter.string(from: date)

You may also want to check your locale identifier.


var locale = Locale.current.identifier

Locale is not only limited to how to display time but also with currency, decimal separator, using metric system, calendar etc.

ISO8601DateFormatter

This is a standard time formatting that being used frequently on web server like Ruby on Rails. New API since iOS 10.

The format is like "2016-11-01T21:10:56Z". Or in dateFormat ""yyyy-MM-dd'T'HH:mm:ssZ". By using this class you don't have to write the dateFormat anymore to avoid mistakes.


let date = Date();
var isoformatter = ISO8601DateFormatter.init()
let timeStr = isoformatter.string(from: date) 
// "2016-11-01T21:14:33Z"

// Generete Date from string that being generated
var dateFromString = isoformatter.date(from: timeStr)
// "Nov 2, 2016, 5:14 AM" <-- valid Date

DateComponents

DateComponents encapsulates the components of a date in an extendable, structured manner. This is particularly useful for UserNotification framework where we can trigger notification via calendar. Example here.

It is used to specify a date by providing the temporal components that make up a date and time in a particular calendar: hour, minutes, seconds, day, month, year, and so on. It can also be used to specify a duration of time, for example, 5 hours and 16 minutes. A DateComponents is not required to define all the component fields.

When a new instance of DateComponents is created, the date components are set to nil.


var dateCompo = DateComponents()
dateCompo.hour = 8
dateCompo.minute = 30
dateCompo.day = 0
dateCompo.calendar = Calendar(identifier: .gregorian)

var myDate = dateCompo.date

var dateFormatter = DateFormatter();
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ EEEE";

var dateString = dateFormatter.string(from: myDate!)
// 0001-12-31 08:30:00 +064646 Sunday

Adding Days to Date


func addDaysfromNow(day: Int) -> Date { return (Calendar.current as NSCalendar).date(byAdding: .day, value: day, to: Date(), options: [])! }

Get a date after adding x days to current date.

Date to String to Date

Sometime we just want to save the date as string. And get it back from string to Date.


// date to string var date = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" var dateString = dateFormatter.string(from:date)

let strTime = "2015-07-27 19:29" let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm" var date = formatter.date(from: strTime)

Just make sure the date format is the same to get the consistent result.

Summary

Here are some of things that we can do with Date with Swift.