How can we Add or subtract the Hours From the current Date Time in C#?
Microsoft Net Framework

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


Upcoming Articles
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM