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

  By Ahsan   Posted on June-07-2023   89

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.

By      07-Jun-2023 Views  89



You may also read following recent Post

Submit Post - Article - Ask a Question - Ask an Interview Question - Submit Useful Links