本文由机器翻译。若要查看英语原文,请勾选“英语”复选框。 也可将鼠标指针移到文本上,在弹出窗口中显示英语原文。
翻译
英语

DateTime 结构

 

表示时间上的一刻,通常以日期和当天的时间表示。

若要浏览此类型的 .NET Framework 源代码,请参阅引用源

命名空间:   System
程序集:  mscorlib(位于 mscorlib.dll)

[SerializableAttribute]
public struct DateTime : IComparable, IFormattable, IConvertible, 
	ISerializable, IComparable<DateTime>, IEquatable<DateTime>

名称说明
System_CAPS_pubmethodDateTime(Int32, Int32, Int32)

DateTime 结构的新实例初始化为指定的年、月和日。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Calendar)

DateTime 结构的新实例初始化为指定日历的指定年、月和日。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32)

DateTime 结构的新实例初始化为指定的年、月、日、小时、分钟和秒。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar)

DateTime 结构的新实例初始化为指定日历的年、月、日、小时、分钟和秒。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)

DateTime 结构的新实例初始化为指定年、月、日、小时、分钟、秒和协调世界时 (UTC) 或本地时间。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32)

DateTime 结构的新实例初始化为指定的年、月、日、小时、分钟、秒和毫秒。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar)

DateTime 结构的新实例初始化为指定日历的指定年、月、日、小时、分钟、秒和毫秒。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind)

DateTime 结构的新实例初始化为指定日历的指定年、月、日、小时、分钟、秒、毫秒和协调世界时 (UTC) 或本地时间。

System_CAPS_pubmethodDateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)

DateTime 结构的新实例初始化为指定年、月、日、小时、分钟、秒、毫秒和协调世界时 (UTC) 或本地时间。

System_CAPS_pubmethodDateTime(Int64)

DateTime 结构的新实例初始化为指定的刻度数。

System_CAPS_pubmethodDateTime(Int64, DateTimeKind)

DateTime 结构的新实例初始化为指定的计时周期数以及协调世界时 (UTC) 或本地时间。

名称说明
System_CAPS_pubpropertyDate

获取此实例的日期部分。

System_CAPS_pubpropertyDay

获取此实例所表示的日期为该月中的第几天。

System_CAPS_pubpropertyDayOfWeek

获取此实例所表示的日期是星期几。

System_CAPS_pubpropertyDayOfYear

获取此实例所表示的日期是该年中的第几天。

System_CAPS_pubpropertyHour

获取此实例所表示日期的小时部分。

System_CAPS_pubpropertyKind

获取一个值,该值指示由此实例表示的时间是基于本地时间、协调世界时 (UTC),还是两者皆否。

System_CAPS_pubpropertyMillisecond

获取此实例所表示日期的毫秒部分。

System_CAPS_pubpropertyMinute

获取此实例所表示日期的分钟部分。

System_CAPS_pubpropertyMonth

获取此实例所表示日期的月份部分。

System_CAPS_pubpropertySystem_CAPS_staticNow

获取一个 DateTime 对象,该对象设置为此计算机上的当前日期和时间,表示为本地时间。

System_CAPS_pubpropertySecond

获取此实例所表示日期的秒部分。

System_CAPS_pubpropertyTicks

获取表示此实例的日期和时间的计时周期数。

System_CAPS_pubpropertyTimeOfDay

获取此实例的当天的时间。

System_CAPS_pubpropertySystem_CAPS_staticToday

获取当前日期。

System_CAPS_pubpropertySystem_CAPS_staticUtcNow

获取一个 DateTime 对象,该对象设置为此计算机上的当前日期和时间,表示为协调通用时间 (UTC)。

System_CAPS_pubpropertyYear

获取此实例所表示日期的年份部分。

名称说明
System_CAPS_pubmethodAdd(TimeSpan)

返回一个新的 DateTime,它将指定 TimeSpan 的值添加到此实例的值上。

System_CAPS_pubmethodAddDays(Double)

返回一个新的 DateTime,它将指定的天数加到此实例的值上。

System_CAPS_pubmethodAddHours(Double)

返回一个新的 DateTime,它将指定的小时数加到此实例的值上。

System_CAPS_pubmethodAddMilliseconds(Double)

返回一个新的 DateTime,它将指定的毫秒数加到此实例的值上。

System_CAPS_pubmethodAddMinutes(Double)

返回一个新的 DateTime,它将指定的分钟数加到此实例的值上。

System_CAPS_pubmethodAddMonths(Int32)

返回一个新的 DateTime,它将指定的月数加到此实例的值上。

System_CAPS_pubmethodAddSeconds(Double)

返回一个新的 DateTime,它将指定的秒数加到此实例的值上。

System_CAPS_pubmethodAddTicks(Int64)

返回一个新的 DateTime,它将指定的刻度数加到此实例的值上。

System_CAPS_pubmethodAddYears(Int32)

返回一个新的 DateTime,它将指定的年份数加到此实例的值上。

System_CAPS_pubmethodSystem_CAPS_staticCompare(DateTime, DateTime)

对两个 DateTime 的实例进行比较,并返回一个指示第一个实例是早于、等于还是晚于第二个实例的整数。

System_CAPS_pubmethodCompareTo(DateTime)

将此实例的值与指定的 DateTime 值相比较,并返回一个整数,该整数指示此实例是早于、等于还是晚于指定的 DateTime 值。

System_CAPS_pubmethodCompareTo(Object)

将此实例的值与包含指定的 DateTime 值的指定对象相比较,并返回一个整数,该整数指示此实例是早于、等于还是晚于指定的 DateTime 值。

System_CAPS_pubmethodSystem_CAPS_staticDaysInMonth(Int32, Int32)

返回指定年和月中的天数。

System_CAPS_pubmethodEquals(DateTime)

返回一个值,该值指示此实例的值是否等于指定 DateTime 实例的值。

System_CAPS_pubmethodSystem_CAPS_staticEquals(DateTime, DateTime)

返回一个值,该值指示的两个 DateTime 实例是否具有同一个日期和时间值。

System_CAPS_pubmethodEquals(Object)

返回一个值,该值指示此实例是否等于指定的对象。(覆盖 ValueType.Equals(Object)。)

System_CAPS_pubmethodSystem_CAPS_staticFromBinary(Int64)

反序列化一个 64 位二进制值,并重新创建序列化的 DateTime 初始对象。

System_CAPS_pubmethodSystem_CAPS_staticFromFileTime(Int64)

将指定的 Windows 文件时间转换为等效的本地时间。

System_CAPS_pubmethodSystem_CAPS_staticFromFileTimeUtc(Int64)

将指定的 Windows 文件时间转换为等效的 UTC 时间。

System_CAPS_pubmethodSystem_CAPS_staticFromOADate(Double)

返回与指定的 OLE 自动化日期等效的 DateTime

System_CAPS_pubmethodGetDateTimeFormats()

将此实例的值转换为标准日期和时间格式说明符支持的所有字符串表示形式。

System_CAPS_pubmethodGetDateTimeFormats(Char)

将此实例的值转换为指定的标准日期和时间格式说明符支持的所有字符串表示形式。

System_CAPS_pubmethodGetDateTimeFormats(Char, IFormatProvider)

将此实例的值转换为指定的标准日期和时间格式说明符和区域性特定格式信息支持的所有字符串表示形式。

System_CAPS_pubmethodGetDateTimeFormats(IFormatProvider)

将此实例的值转换为标准日期和时间格式说明符和指定的区域性特定格式信息支持的所有字符串表示形式。

System_CAPS_pubmethodGetHashCode()

返回此实例的哈希代码。(覆盖 ValueType.GetHashCode()。)

System_CAPS_pubmethodGetType()

获取当前实例的 Type(继承自 Object。)

System_CAPS_pubmethodGetTypeCode()

返回值类型 TypeCodeDateTime

System_CAPS_pubmethodIsDaylightSavingTime()

指示此 DateTime 实例是否在当前时区的夏时制范围内。

System_CAPS_pubmethodSystem_CAPS_staticIsLeapYear(Int32)

返回指定的年份是否为闰年的指示。

System_CAPS_pubmethodSystem_CAPS_staticParse(String)

将日期和时间的字符串表示形式转换为其等效的 DateTime

System_CAPS_pubmethodSystem_CAPS_staticParse(String, IFormatProvider)

使用指定的区域性特定格式设置信息,将日期和时间的字符串表示形式转换为其等效的 DateTime

System_CAPS_pubmethodSystem_CAPS_staticParse(String, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将日期和时间的字符串表示形式转换为其等效的 DateTime

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String, IFormatProvider)

使用指定的格式和区域性特定格式信息,将日期和时间的指定字符串表示形式转换为其等效的 DateTime 字符串表示形式的格式必须与指定的格式完全匹配。

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String, IFormatProvider, DateTimeStyles)

使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 DateTime 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。

System_CAPS_pubmethodSystem_CAPS_staticParseExact(String, String[], IFormatProvider, DateTimeStyles)

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 DateTime 字符串表示形式的格式必须至少与指定的格式之一完全匹配,否则会引发异常。

System_CAPS_pubmethodSystem_CAPS_staticSpecifyKind(DateTime, DateTimeKind)

创建新的 DateTime 对象,该对象具有与指定的 DateTime 相同的刻度数,但是根据指定的 DateTimeKind 值的指示,指定为本地时间或协调世界时 (UTC),或者两者皆否。

System_CAPS_pubmethodSubtract(DateTime)

从此实例中减去指定的日期和时间。

System_CAPS_pubmethodSubtract(TimeSpan)

从此实例中减去指定持续时间。

System_CAPS_pubmethodToBinary()

将当前 DateTime 对象序列化为一个 64 位二进制值,该值随后可用于重新创建 DateTime 对象。

System_CAPS_pubmethodToFileTime()

将当前 DateTime 对象的值转换为 Windows 文件时间。

System_CAPS_pubmethodToFileTimeUtc()

将当前 DateTime 对象的值转换为 Windows 文件时间。

System_CAPS_pubmethodToLocalTime()

将当前 DateTime 对象的值转换为本地时间。

System_CAPS_pubmethodToLongDateString()

将当前 DateTime 对象的值转换为其等效的长日期字符串表示形式。

System_CAPS_pubmethodToLongTimeString()

将当前 DateTime 对象的值转换为其等效的长时间字符串表示形式。

System_CAPS_pubmethodToOADate()

将此实例的值转换为等效的 OLE 自动化日期。

System_CAPS_pubmethodToShortDateString()

将当前 DateTime 对象的值转换为其等效的短日期字符串表示形式。

System_CAPS_pubmethodToShortTimeString()

将当前 DateTime 对象的值转换为其等效的短时间字符串表示形式。

System_CAPS_pubmethodToString()

使用当前的区域性格式约定将当前 DateTime 对象的值转换为它的等效字符串表示形式。(覆盖 ValueType.ToString()。)

System_CAPS_pubmethodToString(IFormatProvider)

使用指定的区域性特定格式信息将当前 DateTime 对象的值转换为它的等效字符串表示形式。

System_CAPS_pubmethodToString(String)

使用指定的格式和当前区域性的格式约定将当前 DateTime 对象的值转换为它的等效字符串表示形式。

System_CAPS_pubmethodToString(String, IFormatProvider)

使用指定的格式和区域性特定格式信息将当前 DateTime 对象的值转换为它的等效字符串表示形式。

System_CAPS_pubmethodToUniversalTime()

将当前 DateTime 对象的值转换为协调世界时 (UTC)。

System_CAPS_pubmethodSystem_CAPS_staticTryParse(String, DateTime)

将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。

System_CAPS_pubmethodSystem_CAPS_staticTryParse(String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的区域性特定格式信息和格式设置样式,将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 DateTime 字符串表示形式的格式必须与指定的格式完全匹配。 该方法返回一个指示转换是否成功的值。

System_CAPS_pubmethodSystem_CAPS_staticTryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 DateTime 字符串表示形式的格式必须至少与指定的格式之一完全匹配。 该方法返回一个指示转换是否成功的值。

名称说明
System_CAPS_pubfieldSystem_CAPS_staticMaxValue

表示 DateTime 的最大可能值。 此字段为只读。

System_CAPS_pubfieldSystem_CAPS_staticMinValue

表示 DateTime 的最小可能值。 此字段为只读。

名称说明
System_CAPS_puboperatorSystem_CAPS_staticAddition(DateTime, TimeSpan)

将指定的时间间隔加到指定的日期和时间以生成新的日期和时间。

System_CAPS_puboperatorSystem_CAPS_staticEquality(DateTime, DateTime)

确定 DateTime 的两个指定的实例是否相等。

System_CAPS_puboperatorSystem_CAPS_staticGreaterThan(DateTime, DateTime)

确定指定的 DateTime 是否晚于另一个指定的 DateTime

System_CAPS_puboperatorSystem_CAPS_staticGreaterThanOrEqual(DateTime, DateTime)

确定一个指定的 DateTime 表示的日期和时间等于还是晚于另一个指定的 DateTime

System_CAPS_puboperatorSystem_CAPS_staticInequality(DateTime, DateTime)

确定 DateTime 的两个指定的实例是否不等。

System_CAPS_puboperatorSystem_CAPS_staticLessThan(DateTime, DateTime)

确定指定的 DateTime 是否早于另一个指定的 DateTime

System_CAPS_puboperatorSystem_CAPS_staticLessThanOrEqual(DateTime, DateTime)

确定一个指定的 DateTime 表示的日期和时间等于还是早于另一个指定的 DateTime

System_CAPS_puboperatorSystem_CAPS_staticSubtraction(DateTime, DateTime)

将指定的日期和时间与另一个指定的日期和时间相减,返回一个时间间隔。

System_CAPS_puboperatorSystem_CAPS_staticSubtraction(DateTime, TimeSpan)

从指定的日期和时间减去指定的时间间隔,返回新的日期和时间。

名称说明
System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToBoolean(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToByte(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToChar(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDateTime(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 返回当前 DateTime 对象。

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDecimal(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDouble(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt16(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt32(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt64(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSByte(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSingle(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToType(Type, IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 将当前 DateTime 对象转换为指定类型的对象。

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt16(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt32(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt64(IFormatProvider)

此 API 支持 产品 基础结构,不应从代码直接使用。 不支持此转换。 尝试使用此方法将引发 InvalidCastException

System_CAPS_pubinterfaceSystem_CAPS_privmethodISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用序列化当前的 SerializationInfo 对象所需的所有数据填充 DateTime 对象。

System_CAPS_note说明

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource-beta.microsoft.com/#mscorlib/system/datetime.cs#df6b1eba7461813b. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

The T:System.DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.

Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the T:System.Globalization.GregorianCalendar calendar (excluding ticks that would be added by leap seconds). For example, a ticks value of 31241376000000000L represents the date, Friday, January 01, 0100 12:00:00 midnight. A T:System.DateTime value is always expressed in the context of an explicit or default calendar.

System_CAPS_note说明

If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the F:System.TimeSpan.TicksPerDay, F:System.TimeSpan.TicksPerHour, F:System.TimeSpan.TicksPerMinute, F:System.TimeSpan.TicksPerSecond, or F:System.TimeSpan.TicksPerMillisecond constant to perform the conversion. For example, to add the number of seconds represented by a specified number of ticks to the P:System.DateTime.Second component of a T:System.DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

In this section:

Instantiating a DateTime object
DateTime values and their string representations
Converting strings to DateTime values
Version considerations
DateTime values
DateTime operations
DateTime resolution
DateTime vs. TimeSpan
DateTime values and calendars
Persisting DateTime values
COM interop considerations

You can create a new T:System.DateTime value in any of the following ways:

  • By calling any of the overloads of the T:System.DateTime constructor that allow you to specify specific elements of the date and time value (such as the year, month, and day, or the number of ticks). The following statement illustrates a call to one of the T:System.DateTime constructors to create a date with a specific year, month, day, hour, minute, and second.

    DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
    
  • By using any compiler-specific syntax for declaring date and time values. For example, the following Visual Basic statement initializes a new T:System.DateTime value.

    Dim date1 As Date = #5/1/2008 8:30:52AM#
    
  • By assigning the T:System.DateTime object a date and time value returned by a property or method. The following example assigns the current date and time, the current Coordinated Universal Time (UTC) date and time, and the current date to three new T:System.DateTime variables.

    DateTime date1 = DateTime.Now;
    DateTime date2 = DateTime.UtcNow;
    DateTime date3 = DateTime.Today;
    
  • By parsing the string representation of a date and time value. The Overload:System.DateTime.Parse, Overload:System.DateTime.ParseExact, Overload:System.DateTime.TryParse, and Overload:System.DateTime.TryParseExact methods all convert a string to its equivalent date and time value. The following example uses the M:System.DateTime.Parse(System.String,System.IFormatProvider) method to parse a string and convert it to a T:System.DateTime value.

    string dateString = "5/1/2008 8:30:52 AM";
    DateTime date1 = DateTime.Parse(dateString, 
                              System.Globalization.CultureInfo.InvariantCulture); 
    

    Note that the Overload:System.DateTime.TryParse and Overload:System.DateTime.TryParseExact methods indicate whether a particular string contains a valid representation of a T:System.DateTime value in addition to performing the conversion.

  • By calling the T:System.DateTime structure's implicit default constructor. (For details on the implicit default constructor of a value type, see Value Types (C# Reference).) An approximate equivalent, for compilers that support it, is declaring a T:System.DateTime value without explicitly assigning a date and time to it. The following example illustrates a call to the T:System.DateTime implicit default constructor in C# and Visual Basic, as well as a T:System.DateTime variable declaration with no assignment in Visual Basic.

    DateTime dat1 = new DateTime();
    // The following method call displays 1/1/0001 12:00:00 AM.
    Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
    // The following method call displays True.
    Console.WriteLine(dat1.Equals(DateTime.MinValue));
    

Internally, all T:System.DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual T:System.DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a T:System.DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation.

Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, the T:System.DateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of its Overload:System.DateTime.ToString method. The default M:System.DateTime.ToString method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default M:System.DateTime.ToString method to display the date and time using the short date and long time pattern for the en-US culture, the current culture on the computer on which the example was run.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString());
// For en-US culture, displays 3/1/2008 7:00:00 AM

The M:System.DateTime.ToString(System.IFormatProvider) method returns the string representation of a date and time value using the short date and long time pattern of a specific culture. The following example uses the M:System.DateTime.ToString(System.IFormatProvider) method to display the date and time using the short date and long time pattern for the fr-FR culture.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 01/03/2008 07:00:00

The M:System.DateTime.ToString(System.String) method returns the string representation of the date and time in a format defined by a standard or custom format specifier and using the formatting conventions of the current culture. The following example uses the M:System.DateTime.ToString(System.String) method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F"));
// Displays Saturday, March 01, 2008 7:00:00 AM

The M:System.DateTime.ToString(System.String,System.IFormatProvider) method returns the string representation of the date and time in a format defined by a specific format specifier and using the formatting conventions of a specific culture. The following example uses the M:System.DateTime.ToString(System.String,System.IFormatProvider) method to display the full date and time pattern for the fr-FR culture.

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F", new System.Globalization.CultureInfo("fr-FR")));
// Displays samedi 1 mars 2008 07:00:00

For more information about formatting T:System.DateTime values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

Parsing involves converting the string representation of a date and time to a T:System.DateTime value. Typically, date and time strings have two different usages in applications:

  • They represent a date and time that can take a variety of forms and that reflect the conventions of either the current culture or a specific culture. For example, an application may allow a user whose current culture is en-US to input a date value as "12/15/2013" or "December 15, 2013", and allow a user whose current culture is en-GB to input a date value as "15/12/2013" or "15 December 2013".

  • They represent a date and time in a predefined format. For example, an application may serialize a date as "20130103" independently of the culture on which the app is running, or it may require that a date be input in the current culture's short date format.

You can use the M:System.DateTime.Parse(System.String) or M:System.DateTime.TryParse(System.String,System.DateTime@) method to convert a string that might reflect one of the common date and time formats used by a culture to a T:System.DateTime value. The following example shows how you can use M:System.DateTime.TryParse(System.String,System.DateTime@) to convert date strings in a number of different culture-specific formats to a T:System.DateTime value. It changes the current culture to English (Great Britain) and calls the M:System.DateTime.GetDateTimeFormats method to generate an array of date and time strings. It then passes each element in the array to the M:System.DateTime.TryParse(System.String,System.DateTime@) method. The output from the example shows that the parsing method was able to successfully convert each of the culture-specific date and time strings.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

      DateTime date1 = new DateTime(2013, 6, 1, 12, 32, 30);
      List<string> badFormats = new List<String>();

      Console.WriteLine("{0,-37} {1,-19}\n", "Date String", "Date");
      foreach (var dateString in date1.GetDateTimeFormats()) {
         DateTime parsedDate;
         if (DateTime.TryParse(dateString, out parsedDate))
            Console.WriteLine("{0,-37} {1,-19}", dateString, DateTime.Parse(dateString));
         else
            badFormats.Add(dateString);
      } 

      // Display strings that could not be parsed.
      if (badFormats.Count > 0) {
         Console.WriteLine("\nStrings that could not be parsed: ");
         foreach (var badFormat in badFormats)
            Console.WriteLine("   {0}", badFormat);         
      }
   }
}
// The example displays the following output:
//       Date String                           Date               
//       
//       01/06/2013                            01/06/2013 00:00:00
//       01/06/13                              01/06/2013 00:00:00
//       1/6/13                                01/06/2013 00:00:00
//       1.6.13                                01/06/2013 00:00:00
//       2013-06-01                            01/06/2013 00:00:00
//       01 June 2013                          01/06/2013 00:00:00
//       1 June 2013                           01/06/2013 00:00:00
//       01 June 2013 12:32                    01/06/2013 12:32:00
//       01 June 2013 12:32                    01/06/2013 12:32:00
//       01 June 2013 12:32 PM                 01/06/2013 12:32:00
//       01 June 2013 12:32 PM                 01/06/2013 12:32:00
//       1 June 2013 12:32                     01/06/2013 12:32:00
//       1 June 2013 12:32                     01/06/2013 12:32:00
//       1 June 2013 12:32 PM                  01/06/2013 12:32:00
//       1 June 2013 12:32 PM                  01/06/2013 12:32:00
//       01 June 2013 12:32:30                 01/06/2013 12:32:30
//       01 June 2013 12:32:30                 01/06/2013 12:32:30
//       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
//       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
//       1 June 2013 12:32:30                  01/06/2013 12:32:30
//       1 June 2013 12:32:30                  01/06/2013 12:32:30
//       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
//       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
//       01/06/2013 12:32                      01/06/2013 12:32:00
//       01/06/2013 12:32                      01/06/2013 12:32:00
//       01/06/2013 12:32 PM                   01/06/2013 12:32:00
//       01/06/2013 12:32 PM                   01/06/2013 12:32:00
//       01/06/13 12:32                        01/06/2013 12:32:00
//       01/06/13 12:32                        01/06/2013 12:32:00
//       01/06/13 12:32 PM                     01/06/2013 12:32:00
//       01/06/13 12:32 PM                     01/06/2013 12:32:00
//       1/6/13 12:32                          01/06/2013 12:32:00
//       1/6/13 12:32                          01/06/2013 12:32:00
//       1/6/13 12:32 PM                       01/06/2013 12:32:00
//       1/6/13 12:32 PM                       01/06/2013 12:32:00
//       1.6.13 12:32                          01/06/2013 12:32:00
//       1.6.13 12:32                          01/06/2013 12:32:00
//       1.6.13 12:32 PM                       01/06/2013 12:32:00
//       1.6.13 12:32 PM                       01/06/2013 12:32:00
//       2013-06-01 12:32                      01/06/2013 12:32:00
//       2013-06-01 12:32                      01/06/2013 12:32:00
//       2013-06-01 12:32 PM                   01/06/2013 12:32:00
//       2013-06-01 12:32 PM                   01/06/2013 12:32:00
//       01/06/2013 12:32:30                   01/06/2013 12:32:30
//       01/06/2013 12:32:30                   01/06/2013 12:32:30
//       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
//       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
//       01/06/13 12:32:30                     01/06/2013 12:32:30
//       01/06/13 12:32:30                     01/06/2013 12:32:30
//       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
//       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
//       1/6/13 12:32:30                       01/06/2013 12:32:30
//       1/6/13 12:32:30                       01/06/2013 12:32:30
//       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
//       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
//       1.6.13 12:32:30                       01/06/2013 12:32:30
//       1.6.13 12:32:30                       01/06/2013 12:32:30
//       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
//       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
//       2013-06-01 12:32:30                   01/06/2013 12:32:30
//       2013-06-01 12:32:30                   01/06/2013 12:32:30
//       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
//       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
//       01 June                               01/06/2013 00:00:00
//       01 June                               01/06/2013 00:00:00
//       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
//       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
//       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
//       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
//       2013-06-01T12:32:30                   01/06/2013 12:32:30
//       12:32                                 22/04/2013 12:32:00
//       12:32                                 22/04/2013 12:32:00
//       12:32 PM                              22/04/2013 12:32:00
//       12:32 PM                              22/04/2013 12:32:00
//       12:32:30                              22/04/2013 12:32:30
//       12:32:30                              22/04/2013 12:32:30
//       12:32:30 PM                           22/04/2013 12:32:30
//       12:32:30 PM                           22/04/2013 12:32:30
//       2013-06-01 12:32:30Z                  01/06/2013 05:32:30
//       01 June 2013 19:32:30                 01/06/2013 19:32:30
//       01 June 2013 19:32:30                 01/06/2013 19:32:30
//       01 June 2013 07:32:30 PM              01/06/2013 19:32:30
//       01 June 2013 7:32:30 PM               01/06/2013 19:32:30
//       1 June 2013 19:32:30                  01/06/2013 19:32:30
//       1 June 2013 19:32:30                  01/06/2013 19:32:30
//       1 June 2013 07:32:30 PM               01/06/2013 19:32:30
//       1 June 2013 7:32:30 PM                01/06/2013 19:32:30
//       June 2013                             01/06/2013 00:00:00
//       June 2013                             01/06/2013 00:00:00

You can use the M:System.DateTime.TryParse(System.String,System.DateTime@) and M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) methods to convert a date and time string that must match a particular format or formats to a T:System.DateTime value. You specify the required format or formats as a parameter to the parsing methodby using one or more or date and time format strings. The following example uses the M:System.DateTime.TryParseExact(System.String,System.String[],System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to T:System.DateTime values.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] formats = { "yyyyMMdd", "HHmmss" };
      string[] dateStrings = { "20130816", "20131608", "  20130816   ", 
                               "115216", "521116", "  115216  " };
      DateTime parsedDate;

      foreach (var dateString in dateStrings) {
         if (DateTime.TryParseExact(dateString, formats, null, 
                                    DateTimeStyles.AllowWhiteSpaces |
                                    DateTimeStyles.AdjustToUniversal,
                                    out parsedDate))
            Console.WriteLine("{0} --> {1:g}", dateString, parsedDate);
         else
            Console.WriteLine("Cannot convert {0}", dateString);
      }
   }
}
// The example displays the following output:
//       20130816 --> 8/16/2013 12:00 AM
//       Cannot convert 20131608
//         20130816    --> 8/16/2013 12:00 AM
//       115216 --> 4/22/2013 11:52 AM
//       Cannot convert 521116
//         115216   --> 4/22/2013 11:52 AM

The M:System.DateTime.Parse(System.String) and M:System.DateTime.ParseExact(System.String,System.String,System.IFormatProvider) methods throw an exception if the string to be converted to a T:System.DateTime value cannot be parsed. The M:System.DateTime.TryParse(System.String,System.DateTime@) and M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) methods return a T:System.Boolean value that indicates whether the conversion succeeded or failed. Because the parsing operation for date and time strings, particularly if strings are input by users, tends to have a high failure rate, and because exception handling is expensive, you should use the M:System.DateTime.TryParse(System.String,System.DateTime@) or M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) methods in scenarios where performance is important or conversions are subject to a high rate of failure.

For more information about parsing date and time values, see Parsing Date and Time Strings in the .NET Framework.

Prior to the .NET Framework version 2.0, the T:System.DateTime structure contains a 64-bit field composed of an unused 2-bit field concatenated with a private Ticks field, which is a 62-bit unsigned field that contains the number of ticks that represent the date and time. The value of the Ticks field can be obtained with the P:System.DateTime.Ticks property.

Starting with the .NET Framework 2.0, the T:System.DateTime structure contains a 64-bit field composed of a private Kind field concatenated with the Ticks field. The Kind field is a 2-bit field that indicates whether the T:System.DateTime structure represents a local time, a Coordinated Universal Time (UTC), or the time in an unspecified time zone. The Kind field is used when performing time conversions between time zones, but not for time comparisons or arithmetic. The value of the Kind field can be obtained with the P:System.DateTime.Kind property.

System_CAPS_note说明

An alternative to the T:System.DateTime structure for working with date and time values in particular time zones is the T:System.DateTimeOffset structure. The T:System.DateTimeOffset structure stores date and time information in a private T:System.DateTime field and the number of minutes by which that date and time differs from UTC in a private T:System.Int16 field. This makes it possible for a T:System.DateTimeOffset value to reflect the time in a particular time zone, whereas a T:System.DateTime value can unambiguously reflect only UTC and the local time zone's time. For a discussion about when to use the T:System.DateTime structure or the T:System.DateTimeOffset structure when working with date and time values, see Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo.

Descriptions of time values in the T:System.DateTime type are often expressed using the Coordinated Universal Time (UTC) standard, which is the internationally recognized name for Greenwich Mean Time (GMT). Coordinated Universal Time is the time as measured at zero degrees longitude, the UTC origin point. Daylight saving time is not applicable to UTC.

Local time is relative to a particular time zone. A time zone is associated with a time zone offset, which is the displacement of the time zone measured in hours from the UTC origin point. In addition, local time is optionally affected by daylight saving time, which adds or subtracts an hour from the length of a day. Consequently, local time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. The time zone offset at the UTC origin point is zero.

UTC time is suitable for calculations, comparisons, and storing dates and time in files. Local time is appropriate for display in user interfaces of desktop applications. Time zone-aware applications (such as many Web applications) also need to work with a number of other time zones.

If the P:System.DateTime.Kind property of a T:System.DateTime object is F:System.DateTimeKind.Unspecified, it is unspecified whether the time represented is local time, UTC time, or a time in some other time zone.

A calculation using a T:System.DateTime structure, such as M:System.DateTime.Add(System.TimeSpan) or M:System.DateTime.Subtract(System.DateTime), does not modify the value of the structure. Instead, the calculation returns a new T:System.DateTime structure whose value is the result of the calculation.

Conversion operations between time zones (such as between UTC and local time, or between one time zone and another) take daylight saving time into account, but arithmetic and comparison operations do not.

The T:System.DateTime structure itself offers limited support for converting from one time zone to another. You can use the M:System.DateTime.ToLocalTime method to convert UTC to local time, or you can use the M:System.DateTime.ToUniversalTime method to convert from local time to UTC. However, a full set of time zone conversion methods is available in the T:System.TimeZoneInfo class. Using these methods, you can convert the time in any one of the world's time zones to the time in any other time zone.

Calculations and comparisons of T:System.DateTime objects are meaningful only if the objects represent times in the same time zone. You can use a T:System.TimeZoneInfo object to represent a T:System.DateTime value's time zone, although the two are loosely coupled. (That is, a T:System.DateTime object does not have a property that returns an object that represents that date and time value's time zone other than the P:System.DateTime.Kind property.) For this reason, in a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a T:System.DateTime object was created. For example, you could use a structure that wraps both the T:System.DateTime value and the T:System.TimeZoneInfo object that represents the T:System.DateTime value's time zone. For details on using UTC in calculations and comparisons with T:System.DateTime values, see Performing Arithmetic Operations with Dates and Times.

Each T:System.DateTime member implicitly uses the Gregorian calendar to perform its operation, with the exception of constructors that specify a calendar, and methods with a parameter derived from T:System.IFormatProvider, such as T:System.Globalization.DateTimeFormatInfo, that implicitly specifies a calendar.

Operations by members of the T:System.DateTime type take into account details such as leap years and the number of days in a month.

Two other common operations with T:System.DateTime values involve converting a date and time value to or from its string representation. The process of converting a T:System.DateTime value to its string representation is a formatting operation; for more information about formatting, see DateTime values and their string representations. The process of converting the string representation of a date and time to a T:System.DateTime value is a parsing operation; for more information about parsing, see Converting strings to DateTime values.

System_CAPS_note说明

As an alternative to performing date and time arithmetic on T:System.DateTime values to measure elapsed time, you can use the T:System.Diagnostics.Stopwatch class.

The P:System.DateTime.Ticks property expresses date and time values in units of one ten-millionth of a second, and the P:System.DateTime.Millisecond property returns the thousandths of a second in a date and time value. However, if you are using repeated calls to the P:System.DateTime.Now property to measure elapsed time, and you are concerned with small time intervals less than 100 milliseconds, you should note that values returned by the P:System.DateTime.Now property are dependent on the system clock, which on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds.

The following example illustrates the dependence of current date and time values on the resolution of the system clock. In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. If the value of the outer loop counter is 10, a call to the M:System.Threading.Thread.Sleep(System.Int32) method introduces a five millisecond delay. As the output from the example shows, the number of milliseconds in returned by the DateTime.Now.Milliseconds property changed only after the call to M:System.Threading.Thread.Sleep(System.Int32).

using System;
using System.Threading;

public class Example
{
   public static void Main()
   {
      String output = "";
      for (int ctr = 0; ctr <= 20; ctr++) {
         output += String.Format("{0}\n", DateTime.Now.Millisecond);
         // Introduce a delay loop.
         for (int delay = 0; delay <= 1000; delay++)
         {}

         if (ctr == 10) {
            output += "Thread.Sleep called...\n";
            Thread.Sleep(5);
         }
      }
      Console.WriteLine(output);
   }
}
// The example displays the following output:
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       111
//       Thread.Sleep called...
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143
//       143

The T:System.DateTime and T:System.TimeSpan value types differ in that a T:System.DateTime represents an instant in time whereas a T:System.TimeSpan represents a time interval. This means, for example, that you can subtract one instance of T:System.DateTime from another to obtain a T:System.TimeSpan object that represents the time interval between them. Or you could add a positive T:System.TimeSpan to the current T:System.DateTime to obtain a T:System.DateTime value that represents a future date.

You can add or subtract a time interval from a T:System.DateTime object. Time intervals can be negative or positive, can be expressed in units such as ticks or seconds, or can be expressed as a T:System.TimeSpan object.

The .NET Framework Class Library includes a number of calendar classes, all of which are derived from the T:System.Globalization.Calendar class. They are:

  • The T:System.Globalization.ChineseLunisolarCalendar class.

  • The T:System.Globalization.EastAsianLunisolarCalendar class.

  • The T:System.Globalization.GregorianCalendar class.

  • The T:System.Globalization.HebrewCalendar class.

  • The T:System.Globalization.HijriCalendar class.

  • The T:System.Globalization.JapaneseCalendar class.

  • The T:System.Globalization.JapaneseLunisolarCalendar class.

  • The T:System.Globalization.JulianCalendar class.

  • The T:System.Globalization.KoreanCalendar class.

  • The T:System.Globalization.KoreanLunisolarCalendar class.

  • The T:System.Globalization.PersianCalendar class.

  • The T:System.Globalization.TaiwanCalendar class.

  • The T:System.Globalization.TaiwanLunisolarCalendar class.

  • The T:System.Globalization.ThaiBuddhistCalendar class.

  • The T:System.Globalization.UmAlQuraCalendar class.

Each culture uses a default calendar defined by its read-only P:System.Globalization.CultureInfo.Calendar property and supports one or more calendars defined by its read-only P:System.Globalization.CultureInfo.OptionalCalendars property. The calendar currently used by a specific T:System.Globalization.CultureInfo object is defined by its P:System.Globalization.DateTimeFormatInfo.Calendar property; it must be one of the calendars found in the P:System.Globalization.CultureInfo.OptionalCalendars array.

A culture's current calendar is used in all formatting operations for that culture. For example, the default calendar of the Persian (Iran) culture is the Umm al-Qura calendar, which is represented by the T:System.Globalization.UmAlQuraCalendar class. When a T:System.Globalization.CultureInfo object that represents the Persian (Iran) culture is used in a date and time formatting operation, the Umm al-Qura calendar is used by default, and the Gregorian calendar is used only if the culture's P:System.Globalization.DateTimeFormatInfo.Calendar property is changed, as the following example shows.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var value = new DateTime(2016, 5, 28);

      Console.WriteLine(value.ToString(faIR));

      faIR.DateTimeFormat.Calendar = new GregorianCalendar();
      Console.WriteLine(value.ToString(faIR));
   }
}
// The example displays the following output:
// 08/03/1395 12:00:00 ?.?
// 28/05/2016 12:00:00 ?.?

A culture's current calendar is also used in all parsing operations for that culture, as the following example shows.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var value = DateTime.Parse("08/03/1395", faIR);
      Console.WriteLine(value.ToString(faIR));

      faIR.DateTimeFormat.Calendar = new GregorianCalendar();
      Console.WriteLine(value.ToString(faIR));
   }
}
// The example displays the following output:
//       08/03/1395 12:00:00 ?.?
//       28/05/2016 12:00:00 ?.?

You can also instantiate a T:System.DateTime value by using the date and time elements (such as the number of the year, month, and day) of a specific calendar by calling a DateTime constructor that includes a calendar parameter and passing it a P:System.Globalization.CultureInfo.Calendar object that represents that calendar. The following example does this by using the date and time elements from the T:System.Globalization.UmAlQuraCalendar calendar.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var dat = new DateTime(1395, 8, 18, faIR.DateTimeFormat.Calendar);
      Console.WriteLine("Umm-al-Qura date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Gregorian date:   {0:d}", dat);
   }
}
// The example displays the following output:
//       Umm-al-Qura date: 18/08/1395
//       Gregorian date:   11/8/2016

DateTime constructors that do not include a calendar parameter assume that the date and time elements are expressed as units in the Gregorian calendar.

All other T:System.DateTime properties and methods use the Gregorian calendar. For example, the P:System.DateTime.Year property returns the year in the Gregorian calendar, and the M:System.DateTime.IsLeapYear(System.Int32) method assumes that the year parameter is a year in the Gregorian calendar. Each T:System.DateTime member that uses the Gregorian calendar has a corresponding member of the P:System.Globalization.CultureInfo.Calendar class that uses a specific calendar. For example, the M:System.Globalization.Calendar.GetYear(System.DateTime) method returns the year in a specific calendar, and the M:System.Globalization.Calendar.IsLeapYear(System.Int32) method interprets the year parameter as a year number in a specific calendar. The following example use both the T:System.DateTime and the corresponding members of the T:System.Globalization.UmAlQuraCalendar class.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var cal = faIR.DateTimeFormat.Calendar;
      var dat = new DateTime(1395, 8, 18, cal);
      Console.WriteLine("Using the Umm-al-Qura calendar:");
      Console.WriteLine("Date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Year: {0}", cal.GetYear(dat));
      Console.WriteLine("Leap year: {0}\n", 
                        cal.IsLeapYear(cal.GetYear(dat)));

      Console.WriteLine("Using the Gregorian calendar:");
      Console.WriteLine("Date: {0:d}", dat);
      Console.WriteLine("Year: {0}", dat.Year);
      Console.WriteLine("Leap year: {0}", DateTime.IsLeapYear(dat.Year));
   }
}
// The example displays the following output:
//       Using the Umm-al-Qura calendar:
//       Date: 18/08/1395
//       Year: 1395
//       Leap year: True
//       
//       Using the Gregorian calendar:
//       Date: 11/8/2016
//       Year: 2016
//       Leap year: True

Although the T:System.DateTime structure includes P:System.DateTime.DayOfWeek property that returns the day of the week in the Gregorian calendar, it does not include a member that allows you to retrieve the week number of the year. To retrieve the week of the year, call the individual calendar's M:System.Globalization.Calendar.GetWeekOfYear(System.DateTime,System.Globalization.CalendarWeekRule,System.DayOfWeek) method. The following example provides an illustration.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      var faIR = new CultureInfo("fa-IR");
      var umAlQura = faIR.DateTimeFormat.Calendar;
      var dat = new DateTime(1395, 8, 18, umAlQura);
      Console.WriteLine("Using the Umm-al-Qura calendar:");
      Console.WriteLine("Date: {0}", dat.ToString("d", faIR));
      Console.WriteLine("Day of Week: {0}", umAlQura.GetDayOfWeek(dat));
      Console.WriteLine("Week of year: {0}\n", 
                        umAlQura.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, 
                                               DayOfWeek.Sunday));

      var greg = new GregorianCalendar(); 
      Console.WriteLine("Using the Gregorian calendar:");
      Console.WriteLine("Date: {0:d}", dat);
      Console.WriteLine("Day of Week: {0}", dat.DayOfWeek);
      Console.WriteLine("Week of year: {0}", 
                         greg.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, 
                                            DayOfWeek.Sunday));
   }
}
// The example displays the following output:
//       Using the Umm-al-Qura calendar:
//       Date: 18/08/1395
//       Day of Week: Tuesday
//       Week of year: 34
//       
//       Using the Gregorian calendar:
//       Date: 11/8/2016
//       Day of Week: Tuesday
//       Week of year: 46

For more information on dates and calendars, see Working with Calendars.

You can persist T:System.DateTime values in four ways:

  • You can convert them to strings and persist the strings.

  • You can convert them to 64-bit integer values (the value of the P:System.DateTime.Ticks property) and persist the integers.

  • You canserialize the DateTime values.

  • You can serialize the DateTime values along with time zone information.

Regardless of which technique you choose, you must ensure that the routine that restores the T:System.DateTime values doesn't lose data or throw an exception. T:System.DateTime values should round-trip. That is, the original value and the restored value should be the same. And if the original T:System.DateTime value represents a single instant of time, it should identify the same moment of time when it's restored.

To successfully restore T:System.DateTime values that are persisted as strings, follow these rules:

  • Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the M:System.DateTime.ToString(System.String,System.IFormatProvider)overload to save the string by using the conventions of the invariant culture, and call the M:System.DateTime.Parse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles) or M:System.DateTime.TryParse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) overload to restore the string by using the conventions of the invariant culture. Never use the M:System.DateTime.ToString, M:System.DateTime.Parse(System.String), or M:System.DateTime.TryParse(System.String,System.DateTime@) overloads, which use the conventions of the current thread culture.

  • If the data represents a single moment of time, ensure that it represents the same moment in time when it's restored, even if it's restored on a system that uses a different time zone. To do this, you convert the T:System.DateTime value to Coordinated Universal Time (UTC) before saving it. You can also serialize the value along with time zone information; for more information about this approach, see Serializing DateTime and time zone data.

The most common error made when persisting T:System.DateTime values as strings is to rely on the formatting conventions of the default or current culture. Problems arise if the current culture is different when saving and restoring the strings. The following example illustrates these problems. It saves five dates using the formatting conventions of the current culture, which in this case is English (United States). It restores the dates using the formatting conventions of the current culture, which in this case is English (Great Britain). Because the formatting conventions of the two cultures are different, two of the dates can't be restored, and the remaining three dates are interpreted incorrectly. Also, if the original date and time values represent single moments in time, the restored times are incorrect because time zone information is lost.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   private const string filename = @".\BadDates.txt";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      string output = null;

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         output += dates[ctr].ToString() + (ctr != dates.Length - 1 ? "|" : "");
      }
      StreamWriter sw = new StreamWriter(filename);
      sw.Write(output);
      sw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      StreamReader sr = new StreamReader(filename);
      string[] inputValues = sr.ReadToEnd().Split( new char[] { '|' } , 
                                                  StringSplitOptions.RemoveEmptyEntries);
      sr.Close();
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var inputValue in inputValues) {
         DateTime dateValue;
         if (DateTime.TryParse(inputValue, out dateValue)) {
            Console.WriteLine("'{0}' --> {1:f}", inputValue, dateValue);
         }
         else {
            Console.WriteLine("Cannot parse '{0}'", inputValue);   
         }
      }
      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       Cannot parse //6/14/2014 6:32:00 AM//
//       //7/10/2014 11:49:00 PM// --> 07 October 2014 23:49
//       //1/10/2015 1:16:00 AM// --> 01 October 2015 01:16
//       Cannot parse //12/20/2014 9:45:00 PM//
//       //6/2/2014 3:14:00 PM// --> 06 February 2014 15:14
//       Restored dates...

To round-trip T:System.DateTime values successfully, follow these steps:

  1. If the values represent single moments of time, convert them from the local time to UTC by calling the M:System.DateTime.ToUniversalTime method.

  2. Convert the dates to their string representations by calling the M:System.DateTime.ToString(System.String,System.IFormatProvider) or M:System.String.Format(System.IFormatProvider,System.String,System.Object[]) overload. Use the formatting conventions of the invariant culture by specifying P:System.Globalization.CultureInfo.InvariantCulture as the provider argument. Specify that the value should round-trip by using the "O" or "R" .

  3. When you call the M:System.DateTime.Parse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles) or M:System.DateTime.TryParse(System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) method.

To restore the persisted T:System.DateTime values without data loss, do the following:

  1. Parse the data by calling the M:System.DateTime.ParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles) or M:System.DateTime.TryParseExact(System.String,System.String,System.IFormatProvider,System.Globalization.DateTimeStyles,System.DateTime@) overload. Specify P:System.Globalization.CultureInfo.InvariantCulture as the provider argument, and use the same standard format string you used for the format argument during conversion. Include the F:System.Globalization.DateTimeStyles.RoundtripKind value in the styles argument.

  2. If the T:System.DateTime values represent single moments in time, call the M:System.DateTime.ToLocalTime method to convert the parsed date from UTC to local time.

The following example uses the invariant culture and the "O" standard format string to ensure that T:System.DateTime values that are saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

public class Example
{
   private const string filename = @".\Dates.txt";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      string output = null;

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         output += dates[ctr].ToUniversalTime().ToString("O", CultureInfo.InvariantCulture) 
                   + (ctr != dates.Length - 1 ? "|" : "");
      }
      StreamWriter sw = new StreamWriter(filename);
      sw.Write(output);
      sw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      StreamReader sr = new StreamReader(filename);
      string[] inputValues = sr.ReadToEnd().Split( new char[] { '|' } , 
                                                  StringSplitOptions.RemoveEmptyEntries);
      sr.Close();
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var inputValue in inputValues) {
         DateTime dateValue;
         if (DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture, 
                               DateTimeStyles.RoundtripKind, out dateValue)) {
            Console.WriteLine("'{0}' --> {1:f}", 
                              inputValue, dateValue.ToLocalTime());
         }
         else {
            Console.WriteLine("Cannot parse '{0}'", inputValue);   
         }
      }
      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       '2014-06-14T13:32:00.0000000Z' --> 14 June 2014 14:32
//       '2014-07-11T06:49:00.0000000Z' --> 11 July 2014 07:49
//       '2015-01-10T09:16:00.0000000Z' --> 10 January 2015 09:16
//       '2014-12-21T05:45:00.0000000Z' --> 21 December 2014 05:45
//       '2014-06-02T22:14:00.0000000Z' --> 02 June 2014 23:14
//       Restored dates...

Instead of persisting a T:System.DateTime value as a string, you can persist it as an T:System.Int64 value that represents a number of ticks. In this case, you don't have to consider the culture of the systems the T:System.DateTime values are persisted and restored on.

To persist a T:System.DateTime value as an integer:

  • If the T:System.DateTime values represent single moments in time, convert them to UTC by calling the M:System.DateTime.ToUniversalTime method.

  • Retrieve the number of ticks represented by the T:System.DateTime value from its P:System.DateTime.Ticks property.

To restore a T:System.DateTime value that has been persisted as an integer:

  1. Instantiate a new T:System.DateTime object by passing the T:System.Int64 value to the M:System.DateTime.#ctor(System.Int64) constructor.

  2. If the T:System.DateTime value represents a single moment in time, convert it from UTC to the local time by calling the M:System.DateTime.ToLocalTime method.

The following example persists an array of T:System.DateTime values as integers on a system in the U.S. Pacific Time zone. It restores it on a system in the UTC zone. The file that contains the integers includes an T:System.Int32 value that indicates the total number of T:System.Int64 values that immediately follow it.

using System;
using System.Globalization;
using System.IO;
using System.Threading;

class Example
{
   private const string filename = @".\IntDates.bin";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      long[] ticks = new long[dates.Length];
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         ticks[ctr] = dates[ctr].ToUniversalTime().Ticks; 
      }
      FileStream fs = new FileStream(filename, FileMode.Create);
      BinaryWriter bw = new BinaryWriter(fs);
      bw.Write(ticks.Length);
      foreach (var tick in ticks)
         bw.Write(tick);

      bw.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
      FileStream fs = new FileStream(filename, FileMode.Open);
      BinaryReader br = new BinaryReader(fs);
      int items;
      DateTime[] dates;

      try { 
         items = br.ReadInt32();
         dates = new DateTime[items];

         for (int ctr = 0; ctr < items; ctr++) {
            long ticks = br.ReadInt64();
            dates[ctr] = new DateTime(ticks).ToLocalTime();
         }
      }   
      catch (EndOfStreamException) {
         Console.WriteLine("File corruption detected. Unable to restore data...");
         return;
      }   
      catch (IOException) {
         Console.WriteLine("Unspecified I/O error. Unable to restore data...");
         return;
      }
      // Thrown during array initialization.
      catch (OutOfMemoryException) {
         Console.WriteLine("File corruption detected. Unable to restore data...");
         return;
      }
      finally {      
         br.Close();
      }   

      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var value in dates)
         Console.WriteLine(value.ToString("f"));

      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       14 June 2014 14:32
//       11 July 2014 07:49
//       10 January 2015 09:16
//       21 December 2014 05:45
//       02 June 2014 23:14
//       Restored dates...

Instead of saving T:System.DateTime values as strings or integers, which you then have to convert back to T:System.DateTime values, you can persist T:System.DateTime values through serialization to a stream or file, and then restore them through deserialization. In this case, T:System.DateTimedata is serialized in some specified object format, and the objects are restored when they are deserialized. A formatter or serializer, such as T:System.Xml.Serialization.XmlSerializer or T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter, handles the process of serialization and deserialization. For more information about serialization and the types of serialization supported by the .NET Framework, see Serialization in the .NET Framework.

The following example uses the T:System.Xml.Serialization.XmlSerializer class to serialize and deserialize T:System.DateTime values that represent all leap year days in the twenty-first century. The output represents the result if the example is run on a system whose current culture is English (Great Britain). Because we've deserialized the T:System.DateTime object itself, the code doesn't have to handle cultural differences in date and time formats.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Xml.Serialization;

class Example
{
   private const string filename = @".\LeapYears.xml";

   public static void Main()
   {
      // Serialize the data.
      List<DateTime> leapYears = new List<DateTime>();
      for (int year = 2000; year <= 2100; year += 4) {
         if (DateTime.IsLeapYear(year)) 
            leapYears.Add(new DateTime(year, 2, 29));
      }
      DateTime[] dateArray = leapYears.ToArray();

      XmlSerializer serializer = new XmlSerializer(dateArray.GetType());
      TextWriter sw = new StreamWriter(filename);

      try {
         serializer.Serialize(sw, dateArray);
      }
      catch (InvalidOperationException e) {
         Console.WriteLine(e.InnerException.Message);         
      }
      finally {
         if (sw != null) sw.Close();
      }   

      // Deserialize the data.
      DateTime[] deserializedDates;
      using (FileStream fs = new FileStream(filename, FileMode.Open)) {
         deserializedDates = (DateTime[]) serializer.Deserialize(fs);
      } 

      // Display the dates.
      Console.WriteLine("Leap year days from 2000-2100 on an {0} system:",
                        Thread.CurrentThread.CurrentCulture.Name);
      int nItems = 0;
      foreach (var dat in deserializedDates) {
         Console.Write("   {0:d}     ", dat);
         nItems++;
         if (nItems % 5 == 0) 
               Console.WriteLine(); 
      }
   }
}
// The example displays the following output:
//    Leap year days from 2000-2100 on an en-GB system:
//       29/02/2000       29/02/2004       29/02/2008       29/02/2012       29/02/2016
//       29/02/2020       29/02/2024       29/02/2028       29/02/2032       29/02/2036
//       29/02/2040       29/02/2044       29/02/2048       29/02/2052       29/02/2056
//       29/02/2060       29/02/2064       29/02/2068       29/02/2072       29/02/2076
//       29/02/2080       29/02/2084       29/02/2088       29/02/2092       29/02/2096

The previous example doesn't include time information. However, if a T:System.DateTime value represents a moment in time and is expressed as a local time, you should convert it from local time to UTC before serializing it by calling the M:System.DateTime.ToUniversalTime method. After you deserialize it, you should convert it from UTC to local time by calling the M:System.DateTime.ToLocalTime method. The following example uses the T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class to serializeT:System.DateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the UTC zone.

using System;
using System.IO;
using System.Globalization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

class Example
{
   private const string filename = @".\Dates.bin";

   public static void Main()
   {
      if (! File.Exists(filename))
         SaveDates();
      else
         RestoreDates();
   }

   private static void SaveDates()
   {
      DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), 
                           new DateTime(2014, 7, 10, 23, 49, 0),  
                           new DateTime(2015, 1, 10, 1, 16, 0), 
                           new DateTime(2014, 12, 20, 21, 45, 0), 
                           new DateTime(2014, 6, 2, 15, 14, 0) }; 
      FileStream fs = new FileStream(filename, FileMode.Create);
      BinaryFormatter bin = new BinaryFormatter();

      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      for (int ctr = 0; ctr < dates.Length; ctr++) { 
         Console.WriteLine(dates[ctr].ToString("f"));
         dates[ctr] = dates[ctr].ToUniversalTime();
      }
      bin.Serialize(fs, dates);
      fs.Close();
      Console.WriteLine("Saved dates...");
   }

   private static void RestoreDates()
   {
      TimeZoneInfo.ClearCachedData();
      Console.WriteLine("Current Time Zone: {0}",
                        TimeZoneInfo.Local.DisplayName);
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

      FileStream fs = new FileStream(filename, FileMode.Open);
      BinaryFormatter bin = new BinaryFormatter();
      DateTime[] dates = (DateTime[]) bin.Deserialize(fs);
      fs.Close();

      Console.WriteLine("The dates on an {0} system:", 
                        Thread.CurrentThread.CurrentCulture.Name);
      foreach (var value in dates)
         Console.WriteLine(value.ToLocalTime().ToString("f"));

      Console.WriteLine("Restored dates...");   
   }
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       14 June 2014 14:32
//       11 July 2014 07:49
//       10 January 2015 09:16
//       21 December 2014 05:45
//       02 June 2014 23:14
//       Restored dates...

The previous examples have all assumed that T:System.DateTime values are expressed as local times, and converted the values between UTC and local time so they reflect the same moment in time on the source and target systems. T:System.DateTime values may also reflect moments in time in a time zone other than local and UTC. In this case, because the T:System.DateTime structure is not time zone-aware, you have to serialize both the T:System.DateTimevalue and the T:System.TimeZoneInfo object that represents its time zone. To do this, create a type whose fields include both the T:System.DateTime value and its time zone. The following example defines a DateWithTimeZone structure that illustrates how this might be done.

using System;

namespace DateTimeExtensions
{
   [Serializable] public struct DateWithTimeZone
   {
      private TimeZoneInfo tz;
      private DateTime dt;

      public DateWithTimeZone(DateTime dateValue, TimeZoneInfo timeZone)
      {
         dt = dateValue;
         if (timeZone == null)
            tz = TimeZoneInfo.Local;
         else
            tz = timeZone;
      }   

      public TimeZoneInfo TimeZone 
      { get { return (tz); }
        set { tz = value; } }

      public DateTime DateTime 
      { get { return (dt); }
        set { dt = value; } }
   }
}
System_CAPS_important重要事项

The DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. To run the examples, first create a class library that contains the DateWithTimeZone structure, and then add a reference to it when you compile each example.

By using the DateWithTimeZone structure , you can then persist date and time along with time zone information. The following example uses the T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class to serialize an array of DateWithTimeZoneobjects.

using System;
using DateTimeExtensions;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
   public static void Main()
   {
      DateWithTimeZone[] dates= { new DateWithTimeZone(new DateTime(2014, 8, 9, 19, 30, 0),  
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
                                  new DateWithTimeZone(new DateTime(2014, 8, 15, 19, 0, 0), 
                                      TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")),  
                                  new DateWithTimeZone(new DateTime(2014, 8, 22, 19, 30, 0),  
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),  
                                  new DateWithTimeZone(new DateTime(2014, 8, 28, 19, 0, 0), 
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")) };
      FileStream fs = new FileStream(@".\Schedule.bin", FileMode.Create);
      BinaryFormatter formatter = new BinaryFormatter();
      try {
         formatter.Serialize(fs, dates);
         // Display dates.
         foreach (var date in dates) {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine("{0} {1}", date.DateTime, 
                              tz.IsDaylightSavingTime(date.DateTime) ? 
                              tz.DaylightName : tz.StandardName);      
         }
      }
      catch (SerializationException e) {
         Console.WriteLine("Serialization failed. Reason: {0}", e.Message);
      }   
      finally {
         if (fs != null) fs.Close();
      }
   }
}
// The example displays the following output:
//       8/9/2014 7:30:00 PM Eastern Daylight Time
//       8/15/2014 7:00:00 PM Pacific Daylight Time
//       8/22/2014 7:30:00 PM Eastern Daylight Time
//       8/28/2014 7:00:00 PM Eastern Daylight Time

The following example then calls the M:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(System.IO.Stream) method to deserialize it.

using System;
using DateTimeExtensions;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
   private const string filename = @".\Schedule.bin";

   public static void Main()
   {
      FileStream fs;
      if (File.Exists(filename))
         fs = new FileStream(filename, FileMode.Open);
      else {
         Console.WriteLine("Unable to find file to deserialize.");
         return;
      }

      BinaryFormatter formatter = new BinaryFormatter();
      DateWithTimeZone[] dates;
      try {
         dates = (DateWithTimeZone[]) formatter.Deserialize(fs);
         // Display dates.
         foreach (var date in dates) {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine("{0} {1}", date.DateTime, 
                              tz.IsDaylightSavingTime(date.DateTime) ? 
                              tz.DaylightName : tz.StandardName);      
         }
      }
      catch (SerializationException e) {
         Console.WriteLine("Deserialization failed. Reason: {0}", e.Message);
      }   
      finally {
         if (fs != null) fs.Close();
      }
   }
}
// The example displays the following output:
//       8/9/2014 7:30:00 PM Eastern Daylight Time
//       8/15/2014 7:00:00 PM Pacific Daylight Time
//       8/22/2014 7:30:00 PM Eastern Daylight Time
//       8/28/2014 7:00:00 PM Eastern Daylight Time

A T:System.DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. However, a T:System.DateTime value that specifies only a time does not round-trip as you might expect.

If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. at 3:00 P.M., instead of January, 1, 0001 C.E. at 3:00 P.M. This happens because the .NET Framework and COM assume a default date when only a time is specified. However, the COM system assumes a base date of December 30, 1899 C.E. while the .NET Framework assumes a base date of January, 1, 0001 C.E.

When only a time is passed from the .NET Framework to COM, special processing is performed that converts the time to the format used by COM. When only a time is passed from COM to the .NET Framework, no special processing is performed because that would corrupt legitimate dates and times on or before December 30, 1899. This also means if a date starts its round-trip from COM, the .NET Framework and COM preserve the date.

The behavior of the .NET Framework and COM means that if your application round-trips a T:System.DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final T:System.DateTime object.

The following example demonstrates how to compare roughly equivalent T:System.DateTime values, accepting a small margin of difference when declaring them equal.

using System;

class DateTimeTester 
{
   static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds)
   {
      long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds 
                                                     % frequencyInSeconds;

      delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;

      return Math.Abs(delta) < windowInSeconds;
	}

	public static void Main() 
	{
      int window = 10;
      int freq = 60 * 60 * 2; // 2 hours;

      DateTime d1 = DateTime.Now;

      DateTime d2 = d1.AddSeconds(2 * window);
      DateTime d3 = d1.AddSeconds(-2 * window);
      DateTime d4 = d1.AddSeconds(window / 2);
      DateTime d5 = d1.AddSeconds(-window / 2);

      DateTime d6 = (d1.AddHours(2)).AddSeconds(2 * window);
      DateTime d7 = (d1.AddHours(2)).AddSeconds(-2 * window);
      DateTime d8 = (d1.AddHours(2)).AddSeconds(window / 2);
      DateTime d9 = (d1.AddHours(2)).AddSeconds(-window / 2);

      Console.WriteLine("d1 ({0}) ~= d1 ({1}): {2}",
                        d1, d1, RoughlyEquals(d1, d1, window, freq));
      Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}", 
                        d1, d2, RoughlyEquals(d1, d2, window, freq));
      Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}", 
                        d1, d3, RoughlyEquals(d1, d3, window, freq));
      Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}", 
                        d1, d4, RoughlyEquals(d1, d4, window, freq));
      Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}", 
                        d1, d5, RoughlyEquals(d1, d5, window, freq));

      Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}", 
                        d1, d6, RoughlyEquals(d1, d6, window, freq));
      Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}", 
                        d1, d7, RoughlyEquals(d1, d7, window, freq));
      Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}", 
                        d1, d8, RoughlyEquals(d1, d8, window, freq));
      Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}", 
                        d1, d9, RoughlyEquals(d1, d9, window, freq));
	}
}
// The example displays output similar to the following:
//    d1 (1/28/2010 9:01:26 PM) ~= d1 (1/28/2010 9:01:26 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d2 (1/28/2010 9:01:46 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d3 (1/28/2010 9:01:06 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d4 (1/28/2010 9:01:31 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d5 (1/28/2010 9:01:21 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d6 (1/28/2010 11:01:46 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d7 (1/28/2010 11:01:06 PM): False
//    d1 (1/28/2010 9:01:26 PM) ~= d8 (1/28/2010 11:01:31 PM): True
//    d1 (1/28/2010 9:01:26 PM) ~= d9 (1/28/2010 11:01:21 PM): True

通用 Windows 平台
自 8 起可用
.NET Framework
自 1.1 起可用
可移植类库
可移植 .NET 平台 中受支持
Silverlight
自 2.0 起可用
Windows Phone Silverlight
自 7.0 起可用
Windows Phone
自 8.1 起可用

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

System_CAPS_caution小心

Assigning an instance of this type is not thread safe on all hardware platforms because the binary representation of that instance might be too large to assign in a single atomic operation.

返回页首
显示: