[edit] Introducing C# TimeSpan
TimeSpan gives the ability for C# to calculate the amount of time between two datetime objects. TimeSpan also has the functionality to add and subtract a given time interval.
- There are 5 overloaded timespan versions
- you can only add and subtract TimeSpan objects with Datetime objects
TimeSpan s = new TimeSpan(2,5,12);
This is how the TimeSpan object is created. Remember, that there are 5 versions of this overloaded class so you don't have to use just this version. Take a look at the following example:
Example 1: This code will simply add a time interval to a datetime class
using System;
class Program
{
static void Main()
{
//One hour interval
TimeSpan MyTimeSpan = new TimeSpan(1, 0, 0);
int year = 1;
int month = 1;
int day = 1;
int hour = 3;
int min = 30;
int sec = 0;
DateTime MyDate = new DateTime(year, month, day, hour, min, sec);
//print ticks
Console.WriteLine(MyDate.ToString("H:mm:ss"));
MyDate += MyTimeSpan; //Add one hour to the current time
Console.WriteLine(MyDate.ToString("H:mm:ss"));
Console.Read();
}
}
Output:
3:30:0
4:30:0
As you can see using the TimeSpan class is simple to use
[edit] C# TimeSpan Properties
|
Property |
Return Type |
Description |
|
Days |
int |
Returns the number of days from a TimeSpan |
|
Hours |
int |
Returns the number of hours from a TimeSpan |
|
Milliseconds |
int |
Returns the number of Milliseconds a TimeSpan |
|
Minutes |
int |
Returns the number of Minutes from a TimeSpan |
|
Seconds |
int |
Returns the number of seconds from a TimeSpan |
|
Ticks |
long |
Returns the number of ticks in a TimeSpan |
|
TotalDays |
double |
Returns the total number of days in a TimeSpan |
|
TotalHours |
double |
Returns the total number of hours in a TimeSpan |
|
TotalMilliseconds |
double |
Returns the total number of Milliseconds of a TimeSpan |
|
TotalMinutes |
double |
Returns the total number of Minutes in a TimeSpan |
|
TotalSeconds |
double |
Returns the total number of seconds in a TimeSpan |
|