I have 2 date objects – start date and end date. I have a requirement where my end date’s time should be an hour after the time of start date i.e. let’s say start date is Feb 12, 3:00 pm and my end date is Feb 15th, but display time for my end date should be 4:00pm i.e. an hour after the start time.
Here is what I tried:
let startDateComponents = Calendar.current.dateComponents([.hour, .minute], from: startDateTime)
print("startDateComponents - (startDateComponents)")
endDateTime = Calendar.current.date(byAdding: .hour, value: 1, to: startDateTime) ?? endDateTime
This works fine when I have both the dates same i.e. Start date is Feb 12th and end date is also Feb 12th, then I get start date as Feb 12, 3:00pm and end date as Feb 12, 4:00pm. However if my end date is Feb 15 and I am expecting end date to Feb 15th, 4:00pm, running the above code gives me Feb 12th, 4:00pm.
How can I create a date object with just change in time?
Also if start date if Feb 12, 11:00pm, when I change the time on end date, it should turn into next date i.e. Feb 16th 00:00am and not Feb 15th 00:00.
2
Answers
The code you’ve submitted above appears to be working for me. Can you provide more details as to the context of your code?
when ran in a playground gave me the current date
"12 Feb 2024 at 4:31 PM"
and an endDateTime of
"13 Feb 2024 at 12:31 AM"
.I’m not 100% sure if that’s what you’re asking, but as far as a bidirectional relationship between start and end date, I would probably implement this with an object along these lines, but you’ll need to adjust based on your own use case.
returns
"Old dates - 2024-02-12 23:42:23 +0000 - 2024-02-13 07:42:23 +0000n"
and"New dates - 4001-01-01 00:00:00 +0000 - 4001-01-01 08:00:00 +0000n"
.Try this approach using
DateComponents
from thestartDate
and theendDate
to construct your
newEndDate
having the same hours, minutes, secondsas the
startDate
.Example code: