Friday, January 11, 2013

System.DateTime and System.TimeSpan


The DateTime type contains data that represents a specific date (month, day, year) and time value, both of which may be formatted in a variety of ways using the supplied members. By way of a simple example, ponder the following statements:

static void Main(string[] args)
{
...
// This constructor takes (year, month, day)
DateTime dt = new DateTime(2004, 10, 17);
// What day of the month is this?
Console.WriteLine("The day of {0} is {1}", dt.Date, dt.DayOfWeek);
dt.AddMonths(2); // Month is now December.
Console.WriteLine("Daylight savings: {0}", dt.IsDaylightSavingTime());
...
}

The TimeSpan structure allows you to easily define and transform units of time using various members, for example:

static void Main(string[] args)
{
...
// This constructor takes (hours, minutes, seconds)
TimeSpan ts = new TimeSpan(4, 30, 0);
Console.WriteLine(ts);
// Subtract 15 minutes from the current TimeSpan and
// print the result.
Console.WriteLine(ts.Subtract(new TimeSpan(0, 15, 0)));
...
}

Figure shows the output of the DateTime and TimeSpan statements



No comments:
Write comments
Recommended Posts × +