Time Steering in Swift 5.5

Sai Durga Mahesh
Geek Culture
Published in
3 min readNov 6, 2021
Photo by Djim Loic on Unsplash

Handling date and time efficiently in App Development is very important. Popular Apps like Twitter, WhatsApp or Instagram uses date and time formatting along with many other operating functions to convey information efficently.

From basic operating functions to very much needed formatting functions, we will recollect everything.

Adding n moments to present day

let tomorrow = Calendar.current.date(byAdding: DateComponents(day: 1), to: Date())let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())

We can go forward/backward for any number of days, months, minutes, hours, seconds and years by changing 1st Calendar.component parameter.

Next Date Requirements

When user wants know what is next possible date where 2nd day of month is tuesday.

Calendar.current.nextDate(after: Date(), matching: DateComponents(day: 2, weekday: 3), matchingPolicy: .strict, repeatedTimePolicy: .first, direction: .forward)

In this way both the forward and backward calculations are possible. Any such requirements with permutations of date, month, year, minutes or seconds can be achieved with this function.

Also, the enumeration of all such possibilities from above method can be made as following:

var i = 8// enumerate above resultCalendar.current.enumerateDates(startingAfter: Date(), matching: DateComponents(day: 2, weekday: 3), matchingPolicy: .strict, repeatedTimePolicy: .first, direction: .forward) { result, exactMatch, stop in   print(result!)   i = i-1   if i == 0 {    stop = true   }}

This gives next 8 results satisfying requirements.

Validating User entered date

Calendar.current.isDateInTomorrow(tomorrow)Calendar.current.isDateInToday(Date())Calendar.current.isDateInWeekend(Date())Calendar.current.isDateInYesterday(yesterday)

With the above methods and similar others, we can validate if user entered date is in weekend/tomorrow/yesterday or not.

Comparison by Granularity

Two date time objects in swift can be compared in swift easily with comparison operators such as <,> or ==.

Date() == Date() //trueDate() < tomorrow! //trueDate() < yesterday! //false

Instead, if you want to compare only by any of components then we can use following

Calendar.current.compare(Date(), to: yesterday, toGranularity: .hour) == .orderedAscending

In addition if we want to compare by all components of time instead of only one then the following is a way

let date1  = Date()let components = Calendar.current.dateComponents([.hour, .minute, .second], from: tomorrow!)let date2 = Calendar.current.date(bySettingHour: components.hour!, minute: components.minute!, second: components.second!, of: Date())!

The transformed datetime object date2 and date1 can be compared with comparison operations or get the difference with the following method.

let difference = Calendar.current.dateComponents([.hour, .minute], from: date1, to: date2)

Symbols

The other useful method is symbols of months and weekdays in various styles can be made up with native methods.

Calendar.current.weekdaySymbolsCalendar.current.shortWeekdaySymbolsCalendar.current.standaloneWeekdaySymbolsCalendar.current.veryShortWeekdaySymbols

Formatting Date and Times

The dragged way of formatting with DateFormatter is replaced by compact way from swift 5.5.

Date().formatted(date: .abbreviated, time: .shortened)

Different combinations of date and time styles can be made up of with simple above function including omission of any component.

In particular, if you want to include, exclude or style individual components such as including date and excluding month can be made up with following

Date().formatted(.dateTime.day().weekday())Date().formatted(.dateTime.hour().minute().weekday(.wide))

Formatting Intervals

Intervals can be formatted as follows

(Date()..<tomorrow!).formatted(date: .numeric, time: .shortened) //"11/7/2021, 1:33 AM – 11/8/2021, 1:33 AM"(Date()..<tomorrow!).formatted(.timeDuration) //"23:59:59"(Date()..<tomorrow!).formatted(.components(style: .abbreviated)) //"23 hr, 59 min, 59 sec"(yesterday!..<Date()).formatted(.components(style: .condensedAbbreviated, fields: [.day])) //"1 day"

Similar to above approach, the painful formatting with RelativeDateFormatter also made easy as follows

tomorrow!.formatted(.relative(presentation: .named, unitsStyle: .wide)) //"tomorrow"tomorrow!.formatted(.relative(presentation: .numeric, unitsStyle: .wide)) //"in 1 day"tomorrow!.formatted(.relative(presentation: .numeric, unitsStyle: .abbreviated)) //"in 24 hr."

That’s it !

Thanks for Reading !!!

👉 Did you find this post useful? You can now support my efforts to keep by buying me a pizza!

--

--

Sai Durga Mahesh
Geek Culture

Using Data Science to provide better solutions to real word problems