WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: adding time in SwiftUI

Forums > SwiftUI

I'm a beginner in SwiftUI but have a basic understanding.

I have messed around with calendar and Date() and can't see to find the simple solution to what i want to do.

I want a user to enter values of time for few activities (i.e. 2 hours for a run and 3 hours bike ride) and then enter a start time of day say.. 11:00am and have dispalyed to the user - run starts 11:00, bike ride starts 1:00pm finished at 4:00pm.

Basically looking for how to do "math" on time of day in swift.

I can post some of my code attempts, but i thought it would be easier to just ask it as a quetsion. Feels like it shoudl be easy and i'm just missing something.

Thank you so much in advance for any help.

1      

If you are working with simple time calculations (i.e., adding a couple of hours to a specific time), you can do this:

let startTime = //get your start time however you want
let endTime = startTime.addingTimeInterval(numberOfHoursToAdd * 60)

But if you want to be entirely correct and account for things like daylight saving time, timespans that cross day or month boundaries, etc, you should do something more like this:

let startTime = //get your start time however you want
let endTime = Calendar.current.date(byAdding: .hour, value: numberOfHoursToAdd, to: startTime)

You can wrap that up in a convenient extension on Date to make it cleaner at the call site:

extension Date {
    func adding(minutes: Int) -> Date {
        Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
    }

    func adding(hours: Int) -> Date {
        Calendar.current.date(byAdding: .hour, value: hours, to: self)!
    }
}

let startTime = Date.now
let endTime = startTime.adding(hours: 3)
print(startTime)
print(endTime)

2      

Thank you so much, that was really helpful. Really appreciate it. Cheers.

1      

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.