C# comes with a really great struct for working with dates and time - it''s called DateTime. It''s not actually a data type, but I have included it in this chapter, because you will often find your self working with dates and/or time using the DateTime struct - sometimes just as much as you work with strings and numbers.Let''s start by instantiating a new DateTime object:
DateTime dt = new DateTime(); Console.WriteLine(dt.ToString());
The result is pretty boring though: 01-01-0001 00:00:00. This corresponds with the DateTime.MinValue field, but DateTime has more helping properties - the most interesting one is the DateTime.Now:
DateTime dt = DateTime.Now; Console.WriteLine(dt.ToString());
This leaves us with the current date and time, which is often very relevant - we will see that in some of the upcoming examples. However, in a lot of situations, you are probably looking to represent a specific date and time - fortunately for us, the DateTime has several constructors to help us with just that. Here's an example:
DateTime dt = new DateTime(2042, 12, 24); Console.WriteLine(dt.ToString());
But what about time? Well, if you don't specify one, it will default to 00:00:00, as you can see from our previous example. You can easily specify time as well though:
DateTime dt = new DateTime(2042, 12, 24, 18, 42, 0); Console.WriteLine(dt.ToString());
DateTime dt = new DateTime(2042, 12, 24, 18, 42, 0); DateTime date = dt.Date; Console.WriteLine(date.ToString());