UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

2      

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)

5      

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

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.