[edit] Using the DateTime.AddHours Method
To use the Datetime AddHours method you will not specify a timespan. You must specify the amount of hours you want to add. It accepts a double value so it can calculate partial hours. Remember, a timespan must NOT be used with DateTime.AddHours.
[edit] Syntax
DateTime.AddHours(<double>)
[edit] Example 1:
using System;
class Program
{
static void Main()
{
DateTime today = DateTime.Now;
Console.WriteLine("today: " + today.ToString());
today = today.AddHours(6);
Console.WriteLine("New Date: " + today.ToString());
Console.Read();
}
}
Output:
today: 4/5/2007 8:09:19 PM
New Date: 4/6/2007 2:09:19 PM
As you can see the AddHours method simply added six hours to the current date.
- Notice: The program also incremented the day, like it was suppose to.
[edit] Example 2:
This example will add partial hours.
using System;
class Program
{
static void Main()
{
DateTime today = DateTime.Now;
Console.WriteLine("today: " + today.ToString());
today = today.AddHours(0.8);
Console.WriteLine("New Date: " + today.ToString());
Console.Read();
}
}
Output:
today: 4/5/2007 8:07:13 PM
New Date: 4/5/2007 8:55:13 PM
As you can see the program added a partial hour and it also added the appropriate minutes and seconds.
<-- DateTime Tutorial
|