Geek Culture
Published in

Geek Culture

Time Steering in Swift 5.5

Photo by Djim Loic on Unsplash

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())

Next Date Requirements

Calendar.current.nextDate(after: Date(), matching: DateComponents(day: 2, weekday: 3), matchingPolicy: .strict, repeatedTimePolicy: .first, direction: .forward)
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   }}

Validating User entered date

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

Comparison by Granularity

Date() == Date() //trueDate() < tomorrow! //trueDate() < yesterday! //false
Calendar.current.compare(Date(), to: yesterday, toGranularity: .hour) == .orderedAscending
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())!
let difference = Calendar.current.dateComponents([.hour, .minute], from: date1, to: date2)

Symbols

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

Formatting Date and Times

Date().formatted(date: .abbreviated, time: .shortened)
Date().formatted(.dateTime.day().weekday())Date().formatted(.dateTime.hour().minute().weekday(.wide))
(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"
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."

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sai Durga Mahesh

Using Data Science to provide better solutions to real word problems