Reputation: 379
I'm working to create a function that takes an input duration and an "end" time, and calculates a "start" time based on that criteria.
Example: if the "end" time is 5:00pm and the "duration" is 30 minutes, then the "start" time returned should be 4:30pm.
I'm getting lost in translating between Int/Date/String, so I may need to re-think my entire approach. So far I'm working with the following, which is just a take on this Stack Overflow post:
var userInputEventEndTime: String
var userInputEventDuration: Int
var userInputEventNeedsToStartTime: String
//Manipulate this function with the input parameters
func makeDate(hr: Int, min: Int, sec: Int) -> Date {
var calendar = Calendar(identifier: .gregorian)
let components = DateComponents(hour: hr, minute: min, second: sec)
let hour = calendar.component(.hour, from: calendar.date(from: components)!)
let minutes = calendar.component(.minute, from: calendar.date(from: components)!)
let seconds = calendar.component(.second, from: calendar.date(from: components)!)
return calendar.date(from: components)!
}
Should I be converting the input strings to DateComponents and then doing the math? If so, I'm not sure how to account for minutes converting to hours. Or just go a different direction altogether? Thanks!
Upvotes: 0
Views: 1111
Reputation: 51892
The following uses DateComponents and Calendar to calculate the start time
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let calendar = Calendar.current
let dateComponents = DateComponents(calendar: calendar, minute: -userInputEventDuration)
if let endTime = dateFormatter.date(from: userInputEventEndTime),
let startTime = calendar.date(byAdding: dateComponents, to: endTime, wrappingComponents: false) {
userInputEventNeedsToStartTime = dateFormatter.string(from: startTime)
}
Here is the same solution written as a function with an example
func calculateStartTime(from endTime: String, duration: Int) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let calendar = Calendar.current
let dateComponents = DateComponents(calendar: calendar, minute: -duration)
if let time = dateFormatter.date(from: endTime),
let startTime = calendar.date(byAdding: dateComponents, to: time, wrappingComponents: false) {
return dateFormatter.string(from: startTime)
}
return nil
}
if let startTime = calculateStartTime(from: "6:00 PM", duration: 30) {
print("Event starts at \(startTime)")
}
Output
Event starts at 05:30 PM
Upvotes: 1
Reputation: 463
To subtract components from the date, just add their negative values.
Upvotes: 0