NEW: Learn SwiftData for free with my all-new book! >>

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)

4      

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

1      

Hacking with Swift is sponsored by Swiftable

SPONSORED An iOS conference hosted in Buenos Aires, Argentina – join us for the third edition from November 29th to December 1st!

Get your ticket

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.