asax asax - 7 months ago 31
C# Question

How to add additional hours to pre-existing time in C#?

I am trying to add additional hours to the pre-existing time. It works when I add with DateTime.Now.AddHours(48) function... This add 48 hours to the current time.

But what I am not able to solve is adding the hours to the time from the past or future.

For example in the code below in "CheckInTime", I am trying to add 48 hours to the pre-existing time(not current time). The "CheckInTime" could be 9/14/2016 9:16:00 PM and I need to add 48 hours to that time. Which should be 9/16/2016 9:16:00 PM

This is a C# code.

DateTime? FutureTime;
DateTime? CheckInTime;

if (duration.Contains("48")) // duration is a time blocks (12 or 24 or 48)hrs
// add 48 hrs from current time
FutureTime= DateTime.Now.AddHours(48);

// should add 48 hrs to the pre-existing time(past or future.)
CheckInTime= GameSchedule.CheckInTime.AddHours(48);
else if (...) // Other code...

What I want to get done: Add hours to the existing time(future or past).


CheckInTime= GameSchedule.CheckInTime.AddHours(48);
//where CheckinTime has past of future time. I want to add 48 hours.


CheckInTime is a DateTime? - a Nullable type - not a DateTime. Thus, you need to extract its Value first:

if (CheckInTime != null) 
    CheckInTime = CheckInTime.Value.AddHours(48);
    // Do whatever you want to do when CheckInTime has not been set yet.

Note: You can directly assign the result of AddHours (which is a DateTime) to CheckInTime (which is a DateTime?), because there is an implicit conversion from every ordinary type to its nullable type.

If you are using Roslyn or above, you can also use the ?. operator instead of the if check:

// Yields null if CheckInTime is null; otherwise, yields the result of the method
// invocation.
CheckInTime = CheckInTime?.AddHours(48);