TimeSpan
In this chapter you will learn:
Get to know TimeSpan
To repesent a period of time, such as 2.5
hours we can use TimeSpan
.
We can create TimeSpan
instances by
using its contructors or using its
fromXXX
methods.
Here are the constructors:
public TimeSpan (int hours, int minutes, int seconds);
public TimeSpan (int days, int hours, int minutes, int seconds);
public TimeSpan (int days, int hours, int minutes, int seconds,int milliseconds);
public TimeSpan (long ticks); // Each tick = 100ns
The static
From...
methods are more convenient:
public static TimeSpan FromDays (double value);
public static TimeSpan FromHours (double value);
public static TimeSpan FromMinutes (double value);
public static TimeSpan FromSeconds (double value);
public static TimeSpan FromMilliseconds (double value);
The following code shows how to create a TimeSpan.
using System;/* java 2 s . c o m*/
using System.Text;
class Sample
{
public static void Main()
{
Console.WriteLine(new TimeSpan(2, 30, 0)); // 02:30:00
Console.WriteLine(TimeSpan.FromHours(2.5)); // 02:30:00
Console.WriteLine(TimeSpan.FromHours(-2.5)); // -02:30:00
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to add time span to another time span
- How to subtract from time span
- Subtract 15 minutes from the current TimeSpan and print the result
Home » C# Tutorial » Date, Time, TimeZone