How can we Add or subtract the Hours From the current Date Time in C#?
How can we Add or subtract the Hours From the current Date Time in C#?
In C#, you can add or subtract hours from the current datetime using the `AddHours()` and `AddHours(-)` methods, respectively. Here are examples of both:
To add hours:
===============csharp code==============
DateTime currentDateTime = DateTime.Now;
DateTime newDateTime = currentDateTime.AddHours(2);
======================================
In this code, `AddHours(2)` adds two hours to the current datetime, storing the result in `newDateTime`.
To subtract hours:
===============csharp code==============
DateTime currentDateTime = DateTime.Now;
DateTime newDateTime = currentDateTime.AddHours(-2);
======================================
In this code, `AddHours(-2)` subtracts two hours from the current datetime, storing the result in `newDateTime`.
Now `newDateTime` will hold the updated datetime based on whether you added or subtracted the hours.
Share This with your friend by choosing any social account