Use the new date and time type in. NET Framework

Source: Internet
Author: User
Tags time zones
Overview

I wrote this article because a friend of the blog Park published one a few days ago. in the NET interview paper, one of the questions about DateTime has aroused heated debate. Since the DateTime type is a medium data type frequently used during development, here we need. NET Framework.

From. NET Framework 1.0, it provides the DateTime type to represent a date and time type, It is a structure type, and cannot be empty, this brings a lot of trouble to some extent when we save data to the database, because we know that the datatime type in the database can be Null. To solve this problem, you have to use DateTime frequently. minValue, but this is not what we want. Fortunately. NET Framework 2.0 provides an empty type. In this case, we can use Nullable <DateTime> to represent a date and time type, which can be Null, this brings us great convenience.

Arrived. NET Framework 3.5 provides us with a brand new date and Time type DateTimeOffset, which is usually expressed by the date and Time relative to Greenwich Mean Time (GMT, Greenwich Mean Time, greenwich Mean Time is also known as the Universal Time Code ). In addition. NET Framework also provides the TimeZone class to indicate the time zone. in NET Framework 3.5, the TimeZone class is further enhanced and the TimeZoneInfo class is provided to represent any time zones in the world.

In this article, we will introduce the date and time types and Time Zone classes in detail.

DateTime and DateTimeOffset

DateTime value type indicates the date and time between midnight, January 1, January 1, 0001 AD and 12:00:00, January 1, December 31, 9999 AD. DateTimeOffset includes a DateTime value and a property named Offset, this attribute 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 Code:

static void Main(string[] args){    Console.WriteLine(DateTime.Now);    Console.WriteLine(DateTimeOffset.Now);}

Output result:

As you can see, DateTime outputs the date and time, and DateTimeOffset not only outputs the date and time, but also the difference between the current time and UTC. Next, let's look at the code to create 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);}

Shows the output result:

Convert DateTime to DateTimeOffset

Through the two examples above, you should have a basic understanding of DateTimeOffset. DateTimeOffset provides a higher degree of Time Zone recognition capability than DateTime, next, let's take a look at how to convert between DateTime and DateTimeOffset. Before we start, let's take a look at the DateTimeKind enumeration. In DateTime, a property named Kind is provided, it indicates whether the DateTime object represents the local time, the International Standard Time (UTC), or neither the local time nor the International Standard Time (UTC ), dateTimeKind is defined as follows:

public enum DateTimeKind{    Unspecified,    Utc,    Local}

For the UTC and local DateTime values, the Offset attribute of the obtained DateTimeOffset value accurately reflects the UTC or local time zone Offset. The following code converts the UTC time to the equivalent DateTimeOffset value:

static void Main(string[] args){    DateTime dateA = new DateTime(2008,8,24,23,33,58);    DateTime dateB = DateTime.SpecifyKind(dateA, DateTimeKind.Utc);    DateTimeOffset dateC = dateB;    Console.WriteLine(dateB);    Console.WriteLine(dateC);}

Shows the output result:

Then, write a code to convert the local time, as shown in the following code:

static void Main(string[] args){    DateTime dateA = new DateTime(2008, 8, 24, 23, 33, 58);    DateTime dateB = DateTime.SpecifyKind(dateA, DateTimeKind.Local);    DateTimeOffset dateC = dateB;    Console.WriteLine(dateB);    Console.WriteLine(dateC);}

Shows the output result:

If the specified time is Unspecified during conversion, the offset of the converted DateTimeOffset value will be the local time zone, as shown in the following code:

static void Main(string[] args){    DateTime dateA = new DateTime(2008, 8, 24, 23, 33, 58);    DateTime dateB = DateTime.SpecifyKind(dateA, DateTimeKind.Unspecified);    DateTimeOffset dateC = dateB;    Console.WriteLine(dateB);    Console.WriteLine(dateC);}

As shown in the output result, the output is the local time zone:

In fact, it can be seen from a DateTime constructor with the DateTimeOffset parameter that only determines whether DateTime is UTC. Otherwise, the offset of the current local time zone is used:

Public DateTimeOffset (DateTime dateTime) {TimeSpan offset; if (dateTime. Kind! = DateTimeKind. utc) {// both Local and Unspecified are converted to Local offset = TimeZone. currentTimeZone. getUtcOffset (dateTime);} else {offset = new TimeSpan (0);} m_offsetMinutes = ValidateOffset (offset); m_dateTime = ValidateDate (dateTime, offset );}
Convert DateTimeOffset to DateTime

When converting a DateTimeOffset type to a DateTime type, you can use the following attributes:

DateTime attribute: returns a DateTime value indicating Unspecified;

UtcDateTime attribute: returns a DateTime value indicating UTC. If the offset is not 0, it is converted to UTC time;

LocalDateTime attribute: returns a DateTime value indicating Local.

The following code defines the three attributes in DateTimeOffset:

public DateTime DateTime {    get {         return ClockDateTime;    }}public DateTime UtcDateTime {    get {         return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);     }} public DateTime LocalDateTime {    get {        return UtcDateTime.ToLocalTime();     }} 

As you can see, in the LocalDateTime attribute, UtcDateTime is obtained first, and then ToLocalTime () is called to convert it to the local time. Now let's look at a group of test code:

static void Main(string[] args){    DateTimeOffset basic = new DateTimeOffset(2008, 8, 24, 23, 33, 58,            new TimeSpan(8,0,0));    DateTime dateA = basic.DateTime;    DateTime dateB = basic.LocalDateTime;    DateTime dateC = basic.UtcDateTime;    Console.WriteLine(basic);    Console.WriteLine("--------------------------");    Console.WriteLine("Unspecified DateTime:" + dateA);    Console.WriteLine("Local DateTIme:" + dateB);    Console.WriteLine("UTC DateTime:" + dateC);}

The final output result is shown in:

 

Select between DateTime and DateTimeOffset

As mentioned above, how can we select between DateTime and DateTimeOffset for the DateTime and DateTimeOffset types? As you can see in the previous example, DateTime can only represent the UTC or local time zone, or the uncertain time zone, which brings great trouble to the porting of our application, unless you specify that it represents UTC, it will be subject to many restrictions when porting the application, such as the following simplest code:

static void Main(string[] args){    DateTime date = DateTime.Now;    Console.WriteLine(date);}

If DateTime represents the local time zone, it is no problem to port the application in the local time zone. However, if your application needs to support different time zones, we recommend that you set the Kind attribute of DateTime to Utc when using it. This is especially important, otherwise, you need to consider using the DateTimeOffset type.

Different from the DateTime type, DateTimeOffset uniquely identifies a specific time point, that is, the time value and the offset relative to UTC. It does not depend on a specific time zone, in most cases, you should consider using DateTimeOffset instead of DateTime type. In addition, SQL Server 2008 also provides support for the DateTimeOffset data type. For details, refer to the new date data type in SQL Server 2008.

However, the DateTimeOffset type is not completely used to replace the DateTime type. In the application, only the date is used, but not the time involved. For example, the date of birth, there is no problem with the DateTime type.

Supported time zones

In. before NET Framework 3.5, we can only use TimeZone to represent a time zone, but the Timezone function is very limited. It can only recognize the local time zone and can be converted Between UTC and local time; timeZoneInfo greatly enhances TimeZone, which can represent any time zone in the world. See the following code:

static void Main(string[] args){    TimeZone timeZoneA = TimeZone.CurrentTimeZone;    Console.WriteLine(timeZoneA.StandardName);    TimeZoneInfo timeZoneB = TimeZoneInfo.Local;    Console.WriteLine(timeZoneB.StandardName);    TimeZoneInfo timeZoneC = TimeZoneInfo.Utc;    Console.WriteLine(timeZoneC.StandardName);}

Shows the output result:

The attributes and methods provided by TimeZone are very limited. TimeZoneInfo is very rich in this respect. We can use TimeZoneInfo to convert the time between two different time zones, as shown in the following code:

static void Main(string[] args){    DateTimeOffset chinaDate = DateTimeOffset.Now;    DateTimeOffset easternDate = TimeZoneInfo.ConvertTime(        chinaDate,        TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));    Console.WriteLine("Now: {0}", chinaDate);    Console.WriteLine("Now in Eastern: {0}", easternDate);}

Shows the output result:

The FindSystemTimeZoneById method is used to obtain the time zone based on the ID. After TimeZoneInfo is released, you can discard the TimeZone class in future development. TimeZoneInfo already fully includes it.

Summary

This article introduces the support for the date and time type in. NET Framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.