Overview
Write this article is due to a few days ago, a friend of the blog Park published an article. NET interview questions, one of the questions about DateTime caused a heated debate, in view of the date and time type is that we will frequently use in the development of a data type, here we need to make a deep understanding of the date-time type in the. NET framework.
Starting with the. NET Framework 1.0, the datetime type is provided to represent a date-time type, which is a struct type and cannot be considered empty, which in part gives us a lot of trouble saving data to the database because we know that Datatime types in a database can be null, and in order to solve this problem, it is often necessary to use datetime.minvalue to express, but this is not what we want. Fortunately, in the. NET Framework 2.0, the nullable types are available, and we can use nullable<datetime> to represent a datetime type, which is nullable, which gives us great convenience.
In the. NET Framework 3.5, we are provided with a new date-time type DateTimeOffset, which is usually represented by the date and time relative to the GMT (Gmt,greenwich Mean). GMT is also referred to as International standard UTC (Universal Time Code). In addition, the. NET Framework also provides us with a timezone class to represent the time zone, and in the. NET Framework 3.5, further enhancements to the TimeZone class provide a TimeZoneInfo class to represent any time zone in the world.
In this article, we'll take a detailed description of the date-time type, the time zone class.
DateTime and DateTimeOffset
The datetime value type represents the date and time between the range of values in the year of January 1, 01, 12:00:00 to the December 31, 9999, and 11:59:59 in A.D.; DateTimeOffset contains a datetime Value and an offset property, which is used to determine the difference between the date and time of the current DateTimeOffset instance and UTC, let's take a look at the output of this piece of code:
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
Console.WriteLine(DateTimeOffset.Now);
}
The output results are:
As you can see, datetime outputs the date and time, and the DateTimeOffset type not only outputs the date and time, but also the difference between the current time and UTC. Next, we'll look at a piece of code, how to construct a datetime and DateTimeOffset instance manually:
static void Main(string[] args)
{
DateTime dateA = new DateTime(2008,8,26,23,1,48);
DateTimeOffset dateB = new DateTimeOffset(2008, 8, 26, 23, 1, 48,
new TimeSpan(4,0,0));
Console.WriteLine(dateA);
Console.WriteLine(dateB);
}
The output is shown in the following illustration: