Click here to Skip to main content
15,882,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two boxes that look like the link below:

dateEdit_NightShiftEndDate and timeEdit_NightShiftEndTime[^]

I populate these boxes with a variable called NightShiftEndDateTime. I'd like to edit this variable to the value set in the boxes when they are changed.

What I have tried:

C#
DateTime NightShiftEndDateTimeToUse = dateEdit_NightShiftEndDate.DateTime.AddHours(-(dateEdit_NightShiftEndDate.DateTime.TimeOfDay.Hours)).AddMinutes(-(dateEdit_NightShiftEndDate.DateTime.TimeOfDay.Minutes));

DateTime NightShiftEndDateTimeToUse2 = NightShiftEndDateTimeToUse.AddHours(timeEdit_NightShiftEndTime.Time.Hour).AddMinutes(timeEdit_NightShiftEndTime.Time.Minute);

NightShiftEndDateTime = NightShiftEndDateTimeToUse2;


This works correctly but it seems like a very long winded way to do something simple. Any advice on how to do this efficiently would be appreciated.
Posted
Updated 24-May-22 5:28am
v2

1 solution

Convert one to a Timespan, and then add it on to the original DateTime:
C#
DateTime start = DateTime.Now.Date;
DateTime end = new DateTime (1970, 1, 1, 8, 30, 0); // Midnight is a good starter.
    // 8 hours, thirty minutes
    // Any year, month, day will do as long as it's a valid DateTime
TimeSpan hoursAndMinutes = end - end.Date;
DateTime endOfShift = start + hoursAndMinutes;
Console.WriteLine($"{start} - {endOfShift}");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900