DateTime.AddHours() Method in C#


The DateTime.AddHours() method in C# is used to add the specified number of hours to the value of this instance. This method returns a new DateTime.

Syntax

Following is the syntax −

public DateTime AddHours (double hrs);

Above, hrs are the number of hours to be added. The value can be negative to subtract the hours.

Example

Let us now see an example to implement the DateTime.AddHours() method

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 2, 9, 0, 10);
      DateTime d2 = d1.AddHours(2);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:t} ", d1);
      System.Console.WriteLine("
New DateTime (After adding hours) = {0:dd} {0:y}, {0:t} ", d2);    } }

Output

This will produce the following output −

Initial DateTime = 02 November 2019, 9:00 AM
New DateTime (After adding hours) = 02 November 2019, 11:00 AM

Example

Let us now see another example to implement the DateTime.AddHours() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 10, 5, 9, 0, 10);
      DateTime d2 = d1.AddHours(-5);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:t} ", d1);
      System.Console.WriteLine("
New DateTime (After subtracting hours) = {0:dd} {0:y}, {0:t} ", d2);    } }

Output

This will produce the following output −

Initial DateTime = 05 October 2019, 9:00 AM
New DateTime (After subtracting hours) = 05 October 2019, 4:00 AM

Updated on: 06-Nov-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements