DateTime DateTime DateTime DateTime Struct

定义

表示时间上的一刻,通常以日期和当天的时间表示。Represents an instant in time, typically expressed as a date and time of day.

public value class DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable, System::Runtime::Serialization::ISerializable
[System.Serializable]
public struct DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable, System.Runtime.Serialization.ISerializable
type DateTime = struct
    interface IFormattable
    interface IConvertible
    interface ISerializable
Public Structure DateTime
Implements IComparable, IComparable(Of DateTime), IConvertible, IEquatable(Of DateTime), IFormattable, ISerializable
继承
属性
实现

注解

重要

日本历法中的年号是根据天皇统治来命名的,因此预计会发生变化。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日在 JapaneseCalendarJapaneseLunisolarCalendar 中标志着令和年号的开始。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 这种年号的变化会影响使用这些日历的所有应用程序。Such a change of era affects all applications that use these calendars. 请参阅 Handling a new era in the Japanese calendar in .NET(使用 .NET 处理日语日历中的新元号),了解详细信息并确定是否会影响你的应用程序。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 请参阅针对日语元号更改准备应用程序,了解有关在 Windows 系统上测试应用程序以确保针对元号更改的准备情况信息。See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. 有关 .Net 中支持多个年号日历的功能,以及在使用支持多个年号的日历时的最佳做法,请参阅使用年号See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.

备注

本文中的一些 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。Some C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行”按钮以在交互窗口中运行示例 。Select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

Try.NET 内联代码运行程序和演练环境的本地时区是协调世界时 (UTC)。The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. 这可能会影响用于说明 DateTimeDateTimeOffsetTimeZoneInfo 类型及其成员的示例的行为和输出。This may affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.

本文包括使用的几个示例DateTime类型:This article includes several examples that use the DateTime type:

初始化示例Initialization Examples

格式设置DateTime以字符串形式的对象Formatting DateTime objects as strings

分析字符串作为DateTime对象Parsing strings as DateTime objects

DateTime 解决方法DateTime resolution

区域性和日历Culture and calendars

持久性Persistence

本部分包含有关的许多常见用法主题DateTime结构:This section contains topics for many common uses of the DateTime struct:

DateTime值类型表示日期和时间的值范围从 00:00:00 (午夜),1 月 1 日 0001 午夜 11:59:59 止 (基督纪元) 通过 11:59:59 PM,到公元 9999 年 12 月 31 日The 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.)在公历。(C.E.) in the Gregorian calendar.

时间值以调用计时周期数为 100 毫微秒为单位进行衡量。Time values are measured in 100-nanosecond units called ticks. 特定日期是自午夜 12:00,公元 0001 年 1 月 1 日以来的计时周期数A particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.)在GregorianCalendar日历。(C.E.) in the GregorianCalendar calendar. 数不包括将闰秒所添加的计时周期数。The number excludes ticks that would be added by leap seconds. 例如,计时周期值 31241376000000000l 表示的日期 0100 年 1 月 1 日,星期五午夜 12:00:00。For example, a ticks value of 31241376000000000L represents the date Friday, January 01, 0100 12:00:00 midnight. 一个DateTime值始终表示上下文的显式或默认日历中。A DateTime value is always expressed in the context of an explicit or default calendar.

备注

如果您正在使用计时周期值,你想要将转换为其他时间间隔,如分钟或秒,则应使用TimeSpan.TicksPerDayTimeSpan.TicksPerHourTimeSpan.TicksPerMinuteTimeSpan.TicksPerSecond,或TimeSpan.TicksPerMillisecond常量来执行此转换。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 TimeSpan.TicksPerDay, TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.TicksPerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. 例如,若要添加的秒数表示的时钟周期到指定数值Second组成部分DateTime值,可以使用表达式dateValue.Second + nTicks/Timespan.TicksPerSecondFor example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

您可以查看这篇文章的示例的整个集的源中任意一种Visual BasicC#从 GitHub 上的 docs 存储库。You can view the source for the entire set of examples from this article in either Visual Basic or C# from the docs repository on GitHub.

备注

一种替代方法DateTime结构,使用日期和时间值中特定时区为DateTimeOffset结构。An alternative to the DateTime structure for working with date and time values in particular time zones is the DateTimeOffset structure. DateTimeOffset结构将日期和时间信息存储在私有DateTime字段和所依据的日期和时间的分钟数与 UTC 的差异在私有Int16字段。The DateTimeOffset structure stores date and time information in a private DateTime field and the number of minutes by which that date and time differs from UTC in a private Int16 field. 这使得DateTimeOffset值以反映特定时区中的时间,而DateTime值可以明确反映仅 UTC 和本地时区的时间。This makes it possible for a DateTimeOffset value to reflect the time in a particular time zone, whereas a DateTime value can unambiguously reflect only UTC and the local time zone's time. 有关何时使用的讨论DateTime结构或DateTimeOffset结构处理日期和时间值时,请参阅选择之间 DateTime、 DateTimeOffset、 TimeSpan 和 TimeZoneInfoFor a discussion about when to use the DateTime structure or the DateTimeOffset structure when working with date and time values, see Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo.

初始化一个 DateTime 对象Initializing a DateTime object

可以将初始值分配到一个新DateTime以多种不同方式的值:You can assign an initial value to a new DateTime value in many different ways:

  • 调用构造函数,在其中指定参数的值,两者中任何一个,或使用隐式默认构造函数。Calling a constructor, either one where you specify arguments for values, or use the implicit default constructor.
  • 分配DateTime到属性或方法的返回值。Assigning a DateTime to the return value of a property or method.
  • 分析DateTime值的字符串表示形式。Parsing a DateTime value from its string representation.
  • 使用 Visual Basic 特定的语言功能来实例化DateTimeUsing Visual Basic-specific language features to instantiate a DateTime.

下面的代码段显示每个的示例:The following code snippets show examples of each:

调用构造函数Invoke Constructors

调用的重载任一DateTime指定元素 (如年、 月和日或计时周期数) 的日期和时间值的构造函数。You call any of the overloads of the DateTime constructor that specify elements of the date and time value (such as the year, month, and day, or the number of ticks). 下面的代码创建一个特定的日期使用DateTime构造函数指定年、 月、 日、 小时、 分钟和秒。The following code creates a specific date using the DateTime constructor specifying the year, month, day, hour, minute, and second.

[!code-vbSystem.DateTime.Instantiation#1][!code-vbSystem.DateTime.Instantiation#1]

var date1 = new DateTime(2008, 5, 1, 8, 30, 52);
Console.WriteLine(date1);

在调用DateTime结构的隐式默认构造函数时所需DateTime初始化为其默认值。You invoke the DateTime structure's implicit default constructor when you want a DateTime initialized to its default value. (有关值类型的隐式默认构造函数的详细信息,请参阅值类型。)某些编译器还支持声明DateTime而无需显式将值分配给它的值。(For details on the implicit default constructor of a value type, see Value Types.) Some compilers also support declaring a DateTime value without explicitly assigning a value to it. 创建没有显式初始化的值也会导致的默认值。Creating a value without an explicit initialization also results in the default value. 下面的示例阐释DateTimeC# 和 Visual Basic 中的隐式默认构造函数以及DateTime声明没有在 Visual Basic 中的分配。The following example illustrates the DateTime implicit default constructor in C# and Visual Basic, as well as a DateTime declaration without assignment in Visual Basic.

[!code-vbSystem.DateTime.Instantiation#5][!code-vbSystem.DateTime.Instantiation#5]

var 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));
分配一个计算的值Assigning a computed value

可以分配DateTime对象的属性或方法返回的日期和时间值。You can assign the DateTime object a date and time value returned by a property or method. 下面的示例将当前日期和时间、 当前的协调世界时 (UTC) 日期和时间和当前日期为三个新DateTime变量。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 DateTime variables.

[!code-vbSystem.DateTime.Instantiation#3][!code-vbSystem.DateTime.Instantiation#3]

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.UtcNow;
DateTime date3 = DateTime.Today;
分析一个字符串,表示日期时间Parsing a string that represents a DateTime

ParseParseExactTryParse,和TryParseExact方法都将字符串转换为其等效的日期和时间值。The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. 下面的示例使用ParseParseExact方法来分析字符串并将其转换为DateTime值。The following examples use the Parse and ParseExact methods to parse a string and convert it to a DateTime value. 第二个格式使用支持的窗体ISO 8601标准层以表示的日期和时间字符串格式。The second format uses a form supported by the ISO 8601 standard for a representing date and time in string format. 此标准表示形式通常用于传输中的 web 服务的日期信息。This standard representation is often used to transfer date information in web services.

[!code-vbSystem.DateTime.Instantiation#4][!code-vbSystem.DateTime.Instantiation#4]

var dateString = "5/1/2008 8:30:52 AM";
DateTime date1 = DateTime.Parse(dateString,
                          System.Globalization.CultureInfo.InvariantCulture);
var iso8601String = "20080501T08:30:52Z";
DateTime dateISO8602 = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ",
                                System.Globalization.CultureInfo.InvariantCulture);

TryParseTryParseExact方法指示字符串是否是有效表示形式DateTime值,以及如果是,执行这一转换。The TryParse and TryParseExact methods indicate whether a string is a valid representation of a DateTime value and, if it is, performs the conversion.

对于 Visual Basic 的特定于语言的语法Language-specific syntax for Visual Basic

以下 Visual Basic 语句初始化新DateTime值。The following Visual Basic statement initializes a new DateTime value.

[!code-vbSystem.DateTime.Instantiation#2][!code-vbSystem.DateTime.Instantiation#2]

日期时间值和其字符串表示形式DateTime values and their string representations

在内部,所有DateTime值表示为 0001 年 1 月 1 日午夜 12:00:00 以来所经历的计时周期 (100 纳秒间隔数) 数。Internally, all 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. 实际DateTime值时显示此值的显示的方式无关。The actual DateTime value is independent of the way in which that value appears when displayed. 外观DateTime值是将值转换为其字符串表示形式的格式设置操作的结果。The appearance of a DateTime value is the result of a formatting operation that converts a value to its string representation.

日期和时间值的外观是依赖于区域性、 国际标准、 应用程序要求和个人首选项。The appearance of date and time values is dependent on culture, international standards, application requirements, and personal preference. DateTime结构格式化日期和时间值通过重载的灵活性ToStringThe DateTime structure offers flexibility in formatting date and time values through overloads of ToString. 默认值DateTime.ToString()方法返回使用当前区域性的短日期和长时间模式的日期和时间值的字符串表示形式。The default DateTime.ToString() method returns the string representation of a date and time value using the current culture's short date and long time pattern. 下面的示例使用默认值DateTime.ToString()方法。The following example uses the default DateTime.ToString() method. 它显示的日期和时间使用当前区域性的短日期和长时间模式。It displays the date and time using the short date and long time pattern for the current culture. EN-US 区域性是在其运行该示例的计算机上的当前区域性。The en-US culture is the current culture on the computer on which the example was run.

[!code-csharpSystem.DateTime.Formatting#1][!code-csharpSystem.DateTime.Formatting#1]

Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString())
' For en-US culture, displays 3/1/2008 7:00:00 AM

您可能需要设置特定区域性中的日期,以支持 web 方案服务器可能在从客户端不同的区域性的格式。You may need to format dates in a specific culture to support web scenarios where the server may be in a different culture from the client. 指定区域性使用DateTime.ToString(IFormatProvider)方法来创建在特定区域性的短日期和长时间表示形式。You specify the culture using the DateTime.ToString(IFormatProvider) method to create the short date and long time representation in a specific culture. 下面的示例使用DateTime.ToString(IFormatProvider)方法来显示日期和时间使用 FR-FR 区域性的短日期和长时间模式。The following example uses the DateTime.ToString(IFormatProvider) method to display the date and time using the short date and long time pattern for the fr-FR culture.

[!code-csharp-interactiveSystem.DateTime.Formatting#2][!code-csharp-interactiveSystem.DateTime.Formatting#2]

Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 01/03/2008 07:00:00

其他应用程序可能需要不同的字符串表示形式的日期。Other applications may require different string representations of a date. DateTime.ToString(String)方法返回通过使用当前区域性的格式设置约定的标准或自定义格式说明符定义的字符串表示形式。The DateTime.ToString(String) method returns the string representation defined by a standard or custom format specifier using the formatting conventions of the current culture. 下面的示例使用DateTime.ToString(String)方法以显示完整的日期和时间模式 en-us 区域性,在其运行该示例的计算机上的当前区域性。The following example uses the DateTime.ToString(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.

[!code-csharpSystem.DateTime.Formatting#3][!code-csharpSystem.DateTime.Formatting#3]

Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F"))
' Displays Saturday, March 01, 2008 7:00:00 AM

最后,可以指定的区域性和格式使用DateTime.ToString(String, IFormatProvider)方法。Finally, you can specify both the culture and the format using the DateTime.ToString(String, IFormatProvider) method. 下面的示例使用DateTime.ToString(String, IFormatProvider)方法以显示完整的日期和时间模式为 FR-FR 区域性。The following example uses the DateTime.ToString(String, IFormatProvider) method to display the full date and time pattern for the fr-FR culture.

[!code-csharp-interactiveSystem.DateTime.Formatting#4][!code-csharp-interactiveSystem.DateTime.Formatting#4]

Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("F", New System.Globalization.CultureInfo("fr-FR")))
' Displays samedi 1 mars 2008 07:00:00

DateTime.ToString(String)重载还可用使用自定义格式字符串来指定其他格式。The DateTime.ToString(String) overload can also be used with a custom format string to specify other formats. 下面的示例演示如何设置格式字符串使用ISO 8601通常用于 web 服务的标准格式。The following example shows how to format a string using the ISO 8601 standard format often used for web services. Iso 8601 格式不具有相应的标准格式字符串。The Iso 8601 format does not have a corresponding standard format string.

[!code-csharp-interactiveSystem.DateTime.Formatting#5][!code-csharp-interactiveSystem.DateTime.Formatting#5]

Dim date1 As Date = #3/1/2008 7:00AM#
Console.WriteLine(date1.ToString("yyyyMMddTHH:mm:ssZ"))
' Displays 20080301T07:00:00Z

有关格式设置的详细信息DateTime值,请参阅标准日期和时间格式字符串自定义日期和时间格式字符串For more information about formatting DateTime values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

从字符串分析的日期时间值Parsing DateTime values from strings

分析日期和时间的字符串表示形式转换DateTime值。Parsing converts the string representation of a date and time to a DateTime value. 通常情况下,日期和时间字符串有两个不同的用法,在应用程序中:Typically, date and time strings have two different usages in applications:

  • 日期和时间采用各种形式,并反映当前区域性或特定区域性的约定。A date and time takes a variety of forms and reflects the conventions of either the current culture or a specific culture. 例如,应用程序允许的用户当前区域性为 EN-US 以"2013 年 12 月 15 日"或"2013 年 12 月 15 日"的形式输入日期值。For example, an application allows a user whose current culture is en-US to input a date value as "12/15/2013" or "December 15, 2013". 它允许的用户当前区域性为 en-gb 以"12/15/2013"或"15 2013 年 12 月。"的形式输入日期值It allows a user whose current culture is en-gb to input a date value as "15/12/2013" or "15 December 2013."

  • 预定义的格式表示日期和时间。A date and time is represented in a predefined format. 例如,应用程序序列化作为"20130103"独立于其运行该应用程序的区域性的日期。For example, an application serializes a date as "20130103" independently of the culture on which the app is running. 应用程序可能需要在当前区域性的短日期格式输入日期。An application may require dates be input in the current culture's short date format.

您使用ParseTryParse方法将字符串转换为区域性使用的常见日期和时间格式之一DateTime值。You use the Parse or TryParse method to convert a string from one of the common date and time formats used by a culture to a DateTime value. 下面的示例演示如何使用TryParse转换到不同的区域性特定格式的日期字符串DateTime值。The following example shows how you can use TryParse to convert date strings in different culture-specific formats to a DateTime value. 将当前区域性更改为英语 (英国),并调用GetDateTimeFormats()方法生成的日期和时间的字符串数组。It changes the current culture to English (Great Britain) and calls the GetDateTimeFormats() method to generate an array of date and time strings. 然后将每个元素传递到的数组TryParse方法。It then passes each element in the array to the TryParse method. 示例输出显示在分析方法已能够成功地将每个特定于区域性的日期和时间字符串转换。The output from the example shows the parsing method was able to successfully convert each of the culture-specific date and time strings.

[!code-csharp-interactiveSystem.DateTime.Parsing#1][!code-csharp-interactiveSystem.DateTime.Parsing#1]

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")

Dim date1 As New DateTime(2013, 6, 1, 12, 32, 30)
Dim badFormats As New List(Of String)

Console.WriteLine($"{"Date String",-37} {"Date",-19}")
Console.WriteLine()
For Each dateString As String In date1.GetDateTimeFormats()
    Dim parsedDate As DateTime
    If DateTime.TryParse(dateString, parsedDate) Then
        Console.WriteLine($"{dateString,-37} {DateTime.Parse(dateString),-19:g}")
    Else
        badFormats.Add(dateString)
    End If
Next

' Display strings that could not be parsed.
If badFormats.Count > 0 Then
    Console.WriteLine()
    Console.WriteLine("Strings that could not be parsed: ")
    For Each badFormat In badFormats
        Console.WriteLine($"   {badFormat}")
    Next
End If
' 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

您使用ParseExactTryParseExact方法将字符串必须匹配特定的格式或格式转换DateTime值。You use the ParseExact and TryParseExact methods to convert a string that must match a particular format or formats to a DateTime value. 作为分析方法的参数指定一个或多个日期和时间格式字符串。You specify one or more date and time format strings as a parameter to the parsing method. 下面的示例使用TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)方法将必须为"yyyyMMdd"格式或"HHmmss"格式的字符串转换DateTime值。The following example uses the TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to DateTime values.

[!code-csharpSystem.DateTime.Parsing#2][!code-csharpSystem.DateTime.Parsing#2]

Dim formats() As String = {"yyyyMMdd", "HHmmss"}
Dim dateStrings() As String = {"20130816", "20131608",
                              "  20130816   ", "115216",
                              "521116", "  115216  "}
Dim parsedDate As DateTime

For Each dateString As String In dateStrings
    If DateTime.TryParseExact(dateString, formats, Nothing,
                           DateTimeStyles.AllowWhiteSpaces Or
                           DateTimeStyles.AdjustToUniversal,
                           parsedDate) Then
        Console.WriteLine($"{dateString} --> {parsedDate:g}")
    Else
        Console.WriteLine($"Cannot convert {dateString}")
    End If
Next
' 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

一个常见用途ParseExact是要转换的字符串表示形式从 web 服务,通常在ISO 8601标准格式。One common use for ParseExact is to convert a string representation from a web service, usually in ISO 8601 standard format. 下面的代码显示了要使用的正确的格式字符串:The following code shows the correct format string to use:

[!code-csharp-interactiveSystem.DateTime.Parsing#3][!code-csharp-interactiveSystem.DateTime.Parsing#3]

Dim iso8601String As String = "20080501T08:30:52Z"
Dim dateISO8602 As DateTime = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ", CultureInfo.InvariantCulture)
Console.WriteLine($"{iso8601String} --> {dateISO8602:g}")

如果无法分析一个字符串,ParseParseExact方法引发异常。If a string cannot be parsed, the Parse and ParseExact methods throw an exception. TryParseTryParseExact方法返回Boolean值,该值指示转换是否成功。The TryParse and TryParseExact methods return a Boolean value that indicates whether the conversion succeeded or failed. 应使用TryParseTryParseExact性能很重要的方案中的方法。You should use the TryParse or TryParseExact methods in scenarios where performance is important. 日期和时间字符串在分析操作往往具有高故障率,并且异常处理将耗费大量资源。The parsing operation for date and time strings tends to have a high failure rate, and exception handling is expensive. 如果用户输入字符串,请使用这些方法或来自未知源。Use these methods if strings are input by users or coming from an unknown source.

有关分析日期和时间值的详细信息,请参阅分析日期和时间字符串For more information about parsing date and time values, see Parsing Date and Time Strings.

日期时间值DateTime values

时间值中的说明DateTime类型通常会表示使用协调世界时 (UTC) 标准。Descriptions of time values in the DateTime type are often expressed using the Coordinated Universal Time (UTC) standard. 协调世界时是国际上认可的名称为格林威治标准时间 (格林威治标准时间)。Coordinated Universal Time is the internationally recognized name for Greenwich Mean Time (GMT). 协调世界时是经度零度,UTC 原点在测量的时间。Coordinated Universal Time is the time as measured at zero degrees longitude, the UTC origin point. 夏时制不适用为 UTC。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. 时区偏移量是时区的以小时的 UTC 起始点的偏移量。A time zone offset 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 a time interval adjustment. 通过将时区偏移量添加到 UTC 和调整为夏时制如有必要计算本地时间。Local time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. 从 UTC 原点的时区偏移量为零。The time zone offset at the UTC origin point is zero.

在文件中是适用于计算、 比较和存储日期和时间的 UTC 时间。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. 此外需要使用大量其他时区的时区感知应用程序 (例如许多 Web 应用程序)。Time zone-aware applications (such as many Web applications) also need to work with a number of other time zones.

如果Kind的属性DateTime对象是DateTimeKind.Unspecified,它是未指定所表示的时间是否是本地时间、 UTC 时间或某些其他时区中的某个时间。If the Kind property of a DateTime object is DateTimeKind.Unspecified, it is unspecified whether the time represented is local time, UTC time, or a time in some other time zone.

日期时间解决方法DateTime resolution

备注

作为执行日期和时间算术运算的替代方法DateTime值度量经过的时间,可以使用Stopwatch类。As an alternative to performing date and time arithmetic on DateTime values to measure elapsed time, you can use the Stopwatch class.

Ticks属性所表达的秒的一千万分之一单位中的日期和时间值。The Ticks property expresses date and time values in units of one ten-millionth of a second. Millisecond属性返回的千分之几秒的日期和时间值中。The Millisecond property returns the thousandths of a second in a date and time value. 使用重复的调用DateTime.Now属性来测量运行时间是依赖于系统时钟。Using repeated calls to the DateTime.Now property to measure elapsed time is dependent on the system clock. Windows 7 和 Windows 8 系统上的系统时钟有大约 15 毫秒。The system clock on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds. 此解析影响较小的时间间隔小于 100 毫秒。This resolution affects small time intervals less than 100 milliseconds.

下面的示例说明了对系统时钟的分辨率的当前日期和时间值的依赖。The following example illustrates the dependence of current date and time values on the resolution of the system clock. 在示例中,外部循环重复执行 20 次,并延迟外部循环内部循环。In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. 如果外部循环计数器的值为 10,调用Thread.Sleep方法引入了五个位数毫秒延迟。If the value of the outer loop counter is 10, a call to the Thread.Sleep method introduces a five-millisecond delay. 下面的示例演示返回的毫秒数DateTime.Now.Milliseconds属性更改仅在调用后的Thread.SleepThe following example shows the number of milliseconds returned by the DateTime.Now.Milliseconds property changes only after the call to Thread.Sleep.

[!code-csharp-interactiveSystem.DateTime.Resolution#1][!code-csharp-interactiveSystem.DateTime.Resolution#1]

Dim output As String = ""
For ctr As Integer = 0 To 20
    output += Date.Now.Millisecond.ToString() + vbCrLf
    ' Introduce a delay loop.
    For delay As Integer = 0 To 1000
    Next

    If ctr = 10 Then
        output += "Thread.Sleep called..." + vbCrLf
        Thread.Sleep(5)
    End If
Next
Console.WriteLine(output)
' The example displays output like the following:
'       111
'       111
'       111
'       111
'       111
'       111
'       111
'       111
'       111
'       111
'       111
'       Thread.Sleep called...
'       143
'       143
'       143
'       143
'       143
'       143
'       143
'       143
'       143
'       143

DateTime 操作DateTime operations

计算使用DateTime结构,如AddSubtract,不会修改该结构的值。A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. 相反,计算返回一个新DateTime结构,其值是计算的结果。Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.

时区 (如 UTC 和本地时间,或两个时区之间) 之间的转换操作会考虑夏时制,但算术运算和比较运算不这样做。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.

DateTime结构本身提供了用于从一个时区转换为另一种有限的支持。The DateTime structure itself offers limited support for converting from one time zone to another. 可以使用ToLocalTime方法将 UTC 转换为本地时间,也可以使用ToUniversalTime方法将从从当地时间转换为 UTC。You can use the ToLocalTime method to convert UTC to local time, or you can use the ToUniversalTime method to convert from local time to UTC. 但是,一套完整的时区转换方法现已推出TimeZoneInfo类。However, a full set of time zone conversion methods is available in the TimeZoneInfo class. 转换时间时区中的任何其他时间使用这些方法中的任何一个世界的时区的时间。You convert the time in any one of the world's time zones to the time in any other time zone using these methods.

计算和比较的DateTime对象是有意义的仅当这些对象表示在相同的时区的时间。Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the same time zone. 可以使用TimeZoneInfo对象来表示DateTime值的时区,尽管两个松散耦合。You can use a TimeZoneInfo object to represent a DateTime value's time zone, although the two are loosely coupled. 一个DateTime对象不具有该属性返回一个对象,表示该日期和时间值的时区。A DateTime object does not have a property that returns an object that represents that date and time value's time zone. Kind属性指示如果DateTime表示 UTC,本地时间,或者是未指定。The Kind property indicates if a DateTime represents UTC, local time, or is unspecified. 中的时区感知应用程序,您必须依赖于一些外部机制来确定在其中时区DateTime创建对象。In a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a DateTime object was created. 可以使用结构来包装DateTime值和TimeZoneInfo对象,表示DateTime值的时区。You could use a structure that wraps both the DateTime value and the TimeZoneInfo object that represents the DateTime value's time zone. 有关详细信息中计算和比较与使用 UTCDateTime值,请参阅日期和时间执行算术运算For details on using UTC in calculations and comparisons with DateTime values, see Performing Arithmetic Operations with Dates and Times.

每个DateTime成员隐式使用公历来执行其操作。Each DateTime member implicitly uses the Gregorian calendar to perform its operation. 例外情况是隐式指定日历的方法。Exceptions are methods that implicitly specify a calendar. 其中包括指定日历的构造函数和方法参数与派生自IFormatProvider,如System.Globalization.DateTimeFormatInfoThese include constructors that specify a calendar, and methods with a parameter derived from IFormatProvider, such as System.Globalization.DateTimeFormatInfo.

操作的成员DateTime类型考虑到闰年和在每月天数等的帐户详细信息。Operations by members of the DateTime type take into account details such as leap years and the number of days in a month.

日期时间值和日历DateTime values and calendars

.NET Framework 类库包括多个日历类,所有这些派生自Calendar类。The .NET Framework Class Library includes a number of calendar classes, all of which are derived from the Calendar class. 它们是:They are:

重要

日本历法中的年号是根据天皇统治来命名的,因此预计会发生变化。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日在 JapaneseCalendarJapaneseLunisolarCalendar 中标志着令和年号的开始。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 这种年号的变化会影响使用这些日历的所有应用程序。Such a change of era affects all applications that use these calendars. 请参阅 Handling a new era in the Japanese calendar in .NET(使用 .NET 处理日语日历中的新元号),了解详细信息并确定是否会影响你的应用程序。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 请参阅针对日语元号更改准备应用程序,了解有关在 Windows 系统上测试应用程序以确保针对元号更改的准备情况信息。See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. 有关 .Net 中支持多个年号日历的功能,以及在使用支持多个年号的日历时的最佳做法,请参阅使用年号See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.

每个区域性使用的默认日历,定义其只读CultureInfo.Calendar属性。Each culture uses a default calendar defined by its read-only CultureInfo.Calendar property. 每个区域性可能会支持一个或多个日历定义其只读CultureInfo.OptionalCalendars属性。Each culture may support one or more calendars defined by its read-only CultureInfo.OptionalCalendars property. 特定于当前使用的日历CultureInfo对象由定义其DateTimeFormatInfo.Calendar属性。The calendar currently used by a specific CultureInfo object is defined by its DateTimeFormatInfo.Calendar property. 它必须是之一中找到的日历CultureInfo.OptionalCalendars数组。It must be one of the calendars found in the CultureInfo.OptionalCalendars array.

区域性的当前日历是该区域性的所有格式设置操作中使用。A culture's current calendar is used in all formatting operations for that culture. 例如,泰国佛区域性的默认日历是由表示泰国佛教日历ThaiBuddhistCalendar类。For example, the default calendar of the Thai Buddhist culture is the Thai Buddhist Era calendar, which is represented by the ThaiBuddhistCalendar class. CultureInfo对象,表示泰国佛区域性使用日期和时间格式设置操作中,默认情况下使用泰国佛教日历。When a CultureInfo object that represents the Thai Buddhist culture is used in a date and time formatting operation, the Thai Buddhist Era calendar is used by default. 公历时才使用区域性的DateTimeFormatInfo.Calendar更改属性,如以下示例所示:The Gregorian calendar is used only if the culture's DateTimeFormatInfo.Calendar property is changed, as the following example shows:

[!code-csharpSystem.DateTime.Calendar#1][!code-csharpSystem.DateTime.Calendar#1]

Dim thTH As New CultureInfo("th-TH")
Dim value As New DateTime(2016, 5, 28)

Console.WriteLine(value.ToString(thTH))

thTH.DateTimeFormat.Calendar = New GregorianCalendar()
Console.WriteLine(value.ToString(thTH))
' The example displays the following output:
'       28/5/2559 0:00:00
'       28/5/2016 0:00:00

如以下示例所示,区域性的当前日历还使用该区域性的所有分析操作中。A culture's current calendar is also used in all parsing operations for that culture, as the following example shows.

[!code-csharpSystem.DateTime.Calendar#2][!code-csharpSystem.DateTime.Calendar#2]

Private Sub ThaiBuddhistEraParse()
    Dim thTH As New CultureInfo("th-TH")
    Dim value As DateTime = DateTime.Parse("28/5/2559", thTH)
    Console.WriteLine(value.ToString(thTH))

    thTH.DateTimeFormat.Calendar = New GregorianCalendar()
    Console.WriteLine(value.ToString(thTH))
    ' The example displays the following output:
    '       28/5/2559 0:00:00
    '       28/5/2016 0:00:00
End Sub

实例化DateTime值使用通过调用日期和时间 (年、 月和日的数) 的元素在特定日历DateTime 构造函数包括calendar参数并将其传递Calendar对象,表示该日历。You instantiate a DateTime value using the date and time elements (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 Calendar object that represents that calendar. 下面的示例使用中的日期和时间元素ThaiBuddhistCalendar日历。The following example uses the date and time elements from the ThaiBuddhistCalendar calendar.

[!code-csharpSystem.DateTime.Calendar#3][!code-csharpSystem.DateTime.Calendar#3]

Dim thTH As New CultureInfo("th-TH")
Dim dat As New DateTime(2559, 5, 28, thTH.DateTimeFormat.Calendar)
Console.WriteLine($"Thai Buddhist Era date: {dat.ToString("d", thTH)}")
Console.WriteLine($"Gregorian date:   {dat:d}")
' The example displays the following output:
'       Thai Buddhist Era Date:  28/5/2559
'       Gregorian Date:     28/05/2016

DateTime 构造函数不包含calendar参数假定为公历日历中的单位表示的日期和时间元素。DateTime constructors that do not include a calendar parameter assume that the date and time elements are expressed as units in the Gregorian calendar.

所有其他DateTime属性和方法使用公历。All other DateTime properties and methods use the Gregorian calendar. 例如,DateTime.Year属性返回公历,年份和DateTime.IsLeapYear(Int32)方法假设year参数是公历日历中的每一年。For example, the DateTime.Year property returns the year in the Gregorian calendar, and the DateTime.IsLeapYear(Int32) method assumes that the year parameter is a year in the Gregorian calendar. 每个DateTime使用公历日历以来的成员都有相应的成员Calendar类,该类使用特定的日历。Each DateTime member that uses the Gregorian calendar has a corresponding member of the Calendar class that uses a specific calendar. 例如,Calendar.GetYear方法返回在特定日历年和Calendar.IsLeapYear方法将解释year特定日历的年数字作为参数。For example, the Calendar.GetYear method returns the year in a specific calendar, and the Calendar.IsLeapYear method interprets the year parameter as a year number in a specific calendar. 下面的示例使用这两个DateTime和相应成员的ThaiBuddhistCalendar类。The following example uses both the DateTime and the corresponding members of the ThaiBuddhistCalendar class.

[!code-csharpSystem.DateTime.Calendar#4][!code-csharpSystem.DateTime.Calendar#4]

Dim thTH As New CultureInfo("th-TH")
Dim cal As Calendar = thTH.DateTimeFormat.Calendar
Dim dat As New DateTime(2559, 5, 28, cal)
Console.WriteLine("Using the Thai Buddhist Era calendar:")
Console.WriteLine($"Date: {dat.ToString("d", thTH)}")
Console.WriteLine($"Year: {cal.GetYear(dat)}")
Console.WriteLine($"Leap year: {cal.IsLeapYear(cal.GetYear(dat))}")
Console.WriteLine()

Console.WriteLine("Using the Gregorian calendar:")
Console.WriteLine($"Date: {dat:d}")
Console.WriteLine($"Year: {dat.Year}")
Console.WriteLine($"Leap year: {DateTime.IsLeapYear(dat.Year)}")
' The example displays the following output:
'       Using the Thai Buddhist Era calendar
'       Date :   28/5/2559
'       Year: 2559
'       Leap year :   True
'
'       Using the Gregorian calendar
'       Date :   28/05/2016
'       Year: 2016
'       Leap year :   True

DateTime结构包含DayOfWeek属性返回公历日历中的日期是星期几。The DateTime structure includes a 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. 若要检索一年中的一周,调用单个日历Calendar.GetWeekOfYear方法。To retrieve the week of the year, call the individual calendar's Calendar.GetWeekOfYear method. 下面的示例进行了这方面的演示。The following example provides an illustration.

[!code-csharpSystem.DateTime.Calendar#5][!code-csharpSystem.DateTime.Calendar#5]

Dim thTH As New CultureInfo("th-TH")
Dim thCalendar As Calendar = thTH.DateTimeFormat.Calendar
Dim dat As New DateTime(1395, 8, 18, thCalendar)
Console.WriteLine("Using the Thai Buddhist Era calendar:")
Console.WriteLine($"Date: {dat.ToString("d", thTH)}")
Console.WriteLine($"Day of Week: {thCalendar.GetDayOfWeek(dat)}")
Console.WriteLine($"Week of year: {thCalendar.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}")
Console.WriteLine()

Dim greg As Calendar = New GregorianCalendar()
Console.WriteLine("Using the Gregorian calendar:")
Console.WriteLine($"Date: {dat:d}")
Console.WriteLine($"Day of Week: {dat.DayOfWeek}")
Console.WriteLine($"Week of year: {greg.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}")
' The example displays the following output:
'       Using the Thai Buddhist Era calendar
'       Date :  18/8/1395
'       Day of Week: Sunday
'       Week of year: 34
'       
'       Using the Gregorian calendar
'       Date :  18/08/0852
'       Day of Week: Sunday
'       Week of year: 34

有关日期和日历的详细信息,请参阅使用日历For more information on dates and calendars, see Working with Calendars.

保存日期时间值Persisting DateTime values

您可以保留DateTime四种方法中的值:You can persist DateTime values in four ways:

必须确保还原的例程DateTime值不会丢失数据或引发的异常无论何种技术选择。You must ensure that the routine that restores the DateTime values doesn't lose data or throw an exception regardless of which technique you choose. DateTime 值应往返。DateTime values should round-trip. 也就是说,原始值和还原的值应为相同。That is, the original value and the restored value should be the same. 如果原始DateTime值表示单个时间实例,它应识别的是同一时刻的还原时的时间。And if the original DateTime value represents a single instant of time, it should identify the same moment of time when it's restored.

以字符串形式的持久保存值Persisting values as strings

已成功还原DateTime保持以字符串形式的值遵循以下规则:To successfully restore DateTime values that are persisted as strings, follow these rules:

最常见的错误时保存所做DateTime以字符串形式的值是依靠默认值或当前区域性的格式设置约定。The most common error made when persisting 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 a different 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.

[!code-csharpSystem.DateTime.Persistence#1][!code-csharpSystem.DateTime.Persistence#1]

Public Sub PersistAsLocalStrings()
    SaveDatesAsStrings()
    RestoreDatesAsStrings()
End Sub

Private Sub SaveDatesAsStrings()
    Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
                          #1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
                          #6/2/2014 3:14PM#}
    Dim output As String = Nothing

    Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For ctr As Integer = 0 To dates.Length - 1
        Console.WriteLine(dates(ctr).ToString("f"))
        output += dates(ctr).ToString() + If(ctr <> dates.Length - 1, "|", "")
    Next
    Dim sw As New StreamWriter(filenameTxt)
    sw.Write(output)
    sw.Close()
    Console.WriteLine("Saved dates...")
End Sub

Private Sub RestoreDatesAsStrings()
    TimeZoneInfo.ClearCachedData()
    Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
    Dim sr As New StreamReader(filenameTxt)
    Dim inputValues As String() = sr.ReadToEnd().Split({"|"c}, StringSplitOptions.RemoveEmptyEntries)
    sr.Close()
    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each inputValue In inputValues
        Dim dateValue As Date
        If DateTime.TryParse(inputValue, dateValue) Then
            Console.WriteLine($"'{inputValue}' --> {dateValue:f}")
        Else
            Console.WriteLine($"Cannot parse '{inputValue}'")
        End If
    Next
    Console.WriteLine("Restored dates...")
End Sub
' 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...

保存/还原DateTime值成功,请执行以下步骤:To round-trip DateTime values successfully, follow these steps:

  1. 如果此值表示单个时刻的时间,将它们转换从从当地时间为 UTC 通过调用ToUniversalTime方法。If the values represent single moments of time, convert them from the local time to UTC by calling the ToUniversalTime method.
  2. 将日期转换为其字符串表示形式,通过调用ToString(String, IFormatProvider)String.Format(IFormatProvider, String, Object[])重载。Convert the dates to their string representations by calling the ToString(String, IFormatProvider) or String.Format(IFormatProvider, String, Object[]) overload. 通过指定使用固定区域性的格式设置约定CultureInfo.InvariantCulture作为provider参数。Use the formatting conventions of the invariant culture by specifying CultureInfo.InvariantCulture as the provider argument. 指定的值应使用"O"或"R"标准格式字符串往返。Specify that the value should round-trip by using the "O" or "R" standard format string.

若要还原的持久DateTime值而不丢失数据,请执行以下步骤:To restore the persisted DateTime values without data loss, follow these steps:

  1. 通过调用分析的数据ParseExactTryParseExact重载。Parse the data by calling the ParseExact or TryParseExact overload. 指定CultureInfo.InvariantCulture作为provider参数,并使用相同的标准格式字符串所用的format在转换过程的参数。Specify CultureInfo.InvariantCulture as the provider argument, and use the same standard format string you used for the format argument during conversion. 包括DateTimeStyles.RoundtripKind中的值styles参数。Include the DateTimeStyles.RoundtripKind value in the styles argument.
  2. 如果DateTime值表示单个时刻,调用ToLocalTime方法,将已分析的日期从 UTC 转换为本地时间。If the DateTime values represent single moments in time, call the ToLocalTime method to convert the parsed date from UTC to local time.

以下示例使用固定区域性和"O"标准格式字符串,请确保DateTime保存和还原的值表示的时间内不考虑系统、 区域性或特定于时区的源和目标系统中是同一时刻。The following example uses the invariant culture and the "O" standard format string to ensure that DateTime values saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems.

[!code-csharpSystem.DateTime.Persistence#2][!code-csharpSystem.DateTime.Persistence#2]

Public Sub PersistAsInvariantStrings()
    SaveDatesAsInvariantStrings()
    RestoreDatesAsInvariantStrings()
End Sub

Private Sub SaveDatesAsInvariantStrings()
    Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
                          #1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
                          #6/2/2014 3:14PM#}
    Dim output As String = Nothing

    Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For ctr As Integer = 0 To dates.Length - 1
        Console.WriteLine(dates(ctr).ToString("f"))
        output += dates(ctr).ToUniversalTime().ToString("O", CultureInfo.InvariantCulture) +
                                   If(ctr <> dates.Length - 1, "|", "")
    Next
    Dim sw As New StreamWriter(filenameTxt)
    sw.Write(output)
    sw.Close()
    Console.WriteLine("Saved dates...")
End Sub

Private Sub RestoreDatesAsInvariantStrings()
    TimeZoneInfo.ClearCachedData()
    Console.WriteLine("Current Time Zone: {0}",
                    TimeZoneInfo.Local.DisplayName)
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
    Dim sr As New StreamReader(filenameTxt)
    Dim inputValues As String() = sr.ReadToEnd().Split({"|"c}, StringSplitOptions.RemoveEmptyEntries)
    sr.Close()
    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each inputValue In inputValues
        Dim dateValue As Date
        If DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture,
                          DateTimeStyles.RoundtripKind, dateValue) Then
            Console.WriteLine($"'{inputValue}' --> {dateValue.ToLocalTime():f}")
        Else
            Console.WriteLine($"Cannot parse '{inputValue}'")
        End If
    Next
    Console.WriteLine("Restored dates...")
End Sub
' 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...
持久保存值作为整数Persisting values as integers

您可以保留日期和时间作为Int64值,该值表示计时周期数。You can persist a date and time as an Int64 value that represents a number of ticks. 在这种情况下,您无需考虑的系统区域性DateTime值是保留和还原。In this case, you don't have to consider the culture of the systems the DateTime values are persisted and restored on.

若要持久保存DateTime为整数的值:To persist a DateTime value as an integer:

  • 如果DateTime值表示单个时刻,将其转换为 UTC,通过调用ToUniversalTime方法。If the DateTime values represent single moments in time, convert them to UTC by calling the ToUniversalTime method.
  • 检索所表示的计时周期数DateTime值从其Ticks属性。Retrieve the number of ticks represented by the DateTime value from its Ticks property.

若要还原DateTime已保存为整数的值:To restore a DateTime value that has been persisted as an integer:

  1. 实例化一个新DateTime对象通过传递Int64值设为DateTime(Int64)构造函数。Instantiate a new DateTime object by passing the Int64 value to the DateTime(Int64) constructor.
  2. 如果DateTime值表示单个时刻,它从 UTC 转换为本地时间通过调用ToLocalTime方法。If the DateTime value represents a single moment in time, convert it from UTC to the local time by calling the ToLocalTime method.

下面的示例仍然存在一个数组DateTime美国中的系统上的整数值。The following example persists an array of DateTime values as integers on a system in the U.S. Pacific Time zone. 它在 UTC 时区的系统上将其还原。It restores it on a system in the UTC zone. 包含整数的文件包括Int32值,该值指示的总数Int64紧挨着它的值。The file that contains the integers includes an Int32 value that indicates the total number of Int64 values that immediately follow it.

[!code-csharpSystem.DateTime.Persistence#3][!code-csharpSystem.DateTime.Persistence#3]

Public Sub PersistAsIntegers()
    SaveDatesAsIntegers()
    RestoreDatesAsIntegers()
End Sub

Private Sub SaveDatesAsIntegers()
    Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
                          #1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
                          #6/2/2014 3:14PM#}

    Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    Dim ticks(dates.Length - 1) As Long
    For ctr As Integer = 0 To dates.Length - 1
        Console.WriteLine(dates(ctr).ToString("f"))
        ticks(ctr) = dates(ctr).ToUniversalTime().Ticks
    Next
    Dim fs As New FileStream(filenameInts, FileMode.Create)
    Dim bw As New BinaryWriter(fs)
    bw.Write(ticks.Length)
    For Each tick In ticks
        bw.Write(tick)
    Next
    bw.Close()
    Console.WriteLine("Saved dates...")
End Sub

Private Sub RestoreDatesAsIntegers()
    TimeZoneInfo.ClearCachedData()
    Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
    Dim fs As New FileStream(filenameInts, FileMode.Open)
    Dim br As New BinaryReader(fs)
    Dim items As Integer
    Dim dates As DateTime()

    Try
        items = br.ReadInt32()
        ReDim dates(items - 1)

        For ctr As Integer = 0 To items - 1
            Dim ticks As Long = br.ReadInt64()
            dates(ctr) = New DateTime(ticks).ToLocalTime()
        Next
    Catch e As EndOfStreamException
        Console.WriteLine("File corruption detected. Unable to restore data...")
        Exit Sub
    Catch e As IOException
        Console.WriteLine("Unspecified I/O error. Unable to restore data...")
        Exit Sub
    Catch e As OutOfMemoryException     'Thrown in array initialization.
        Console.WriteLine("File corruption detected. Unable to restore data...")
        Exit Sub
    Finally
        br.Close()
    End Try

    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each value In dates
        Console.WriteLine(value.ToString("f"))
    Next
    Console.WriteLine("Restored dates...")
End Sub
' 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...

序列化的日期时间值Serializing DateTime values

您可以保留DateTime值通过序列化到流或文件,然后还原它们通过反序列化。You can persist DateTime values through serialization to a stream or file, and then restore them through deserialization. DateTime 一些指定的对象格式序列化数据。DateTime data is serialized in some specified object format. 它们反序列化时,将还原对象。The objects are restored when they are deserialized. 格式化程序或序列化程序,如XmlSerializerBinaryFormatter,处理序列化和反序列化的过程。A formatter or serializer, such as XmlSerializer or BinaryFormatter, handles the process of serialization and deserialization. 有关序列化和类型的序列化.NET Framework 支持的详细信息,请参阅序列化For more information about serialization and the types of serialization supported by the .NET Framework, see Serialization.

下面的示例使用XmlSerializer类进行序列化和反序列化DateTime值。The following example uses the XmlSerializer class to serialize and deserialize DateTime values. 这些值表示所有闰年天内,第 21 世纪中。The values 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). 因为已反序列化DateTime对象本身,代码无需处理日期和时间格式的区域性差异。Because you've deserialized the DateTime object itself, the code doesn't have to handle cultural differences in date and time formats.

[!code-csharpSystem.DateTime.Persistence#4][!code-csharpSystem.DateTime.Persistence#4]

Public Sub PersistAsXml()
    ' Serialize the data.
    Dim leapYears As New List(Of DateTime)()
    For year As Integer = 2000 To 2100 Step 4
        If Date.IsLeapYear(year) Then
            leapYears.Add(New Date(year, 2, 29))
        End If
    Next
    Dim dateArray As DateTime() = leapYears.ToArray()

    Dim serializer As New XmlSerializer(dateArray.GetType())
    Dim sw As TextWriter = New StreamWriter(filenameXml)

    Try
        serializer.Serialize(sw, dateArray)
    Catch e As InvalidOperationException
        Console.WriteLine(e.InnerException.Message)
    Finally
        If sw IsNot Nothing Then sw.Close()
    End Try

    ' Deserialize the data.
    Dim deserializedDates As Date()
    Using fs As New FileStream(filenameXml, FileMode.Open)
        deserializedDates = CType(serializer.Deserialize(fs), Date())
    End Using

    ' Display the dates.
    Console.WriteLine($"Leap year days from 2000-2100 on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    Dim nItems As Integer
    For Each dat In deserializedDates
        Console.Write($"   {dat:d}     ")
        nItems += 1
        If nItems Mod 5 = 0 Then Console.WriteLine()
    Next
End Sub
' 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. 如果DateTime值表示某个时刻,表示为本地时间,将它转换从从当地时间为 UTC 之前通过调用序列化ToUniversalTime方法。If a DateTime value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the ToUniversalTime method. 在反序列化后,它从 UTC 转换为本地时间通过调用ToLocalTime方法。After you deserialize it, convert it from UTC to local time by calling the ToLocalTime method. 下面的示例使用BinaryFormatter类来序列化DateTime美国的系统上的数据太平洋标准时区并以其在美国中的系统上反序列化中央标准区域。The following example uses the BinaryFormatter class to serialize DateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the U.S. Central Standard zone.

[!code-csharpSystem.DateTime.Persistence#5][!code-csharpSystem.DateTime.Persistence#5]

Public Sub PersistBinary()
    SaveDatesBinary()
    RestoreDatesBinary()
End Sub

Private Sub SaveDatesBinary()
    Dim dates As Date() = {#6/14/2014 6:32AM#, #7/10/2014 11:49PM#,
                          #1/10/2015 1:16AM#, #12/20/2014 9:45PM#,
                          #6/2/2014 3:14PM#}
    Dim fs As New FileStream(filenameBin, FileMode.Create)
    Dim bin As New BinaryFormatter()

    Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Console.WriteLine("The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For ctr As Integer = 0 To dates.Length - 1
        Console.WriteLine(dates(ctr).ToString("f"))
        dates(ctr) = dates(ctr).ToUniversalTime()
    Next
    bin.Serialize(fs, dates)
    fs.Close()
    Console.WriteLine("Saved dates...")
End Sub

Private Sub RestoreDatesBinary()
    TimeZoneInfo.ClearCachedData()
    Console.WriteLine("Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")

    Dim fs As New FileStream(filenameBin, FileMode.Open)
    Dim bin As New BinaryFormatter()
    Dim dates As DateTime() = DirectCast(bin.Deserialize(fs), Date())
    fs.Close()

    Console.WriteLine("The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each value In dates
        Console.WriteLine(value.ToLocalTime().ToString("f"))
    Next
    Console.WriteLine("Restored dates...")
End Sub
' 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-6:00) Central Time (US & Canada)
'       The dates on an en-GB system:
'       14 June 2014 08:32
'       11 July 2014 01:49
'       10 January 2015 03:16
'       20 December 2014 11:45
'       02 June 2014 17:14
'       Restored dates...

序列化日期时间和时区的数据Serializing DateTime and time zone data

所有前面的示例假定DateTime值表示为本地时间。The previous examples all assumed that DateTime values are expressed as local times. 代码转换 UTC 与当地时间之间的值,使其反映在源和目标系统上的同一时刻。The code converted the values between UTC and local time so they reflect the same moment in time on the source and target systems. DateTime 值还可能反映在非本地时区与 UTC 时间的时间。DateTime values may also reflect moments in time in a time zone other than local and UTC. 因为DateTime结构不识别时区,则必须序列化都DateTime值和TimeZoneInfo对象,表示其时区。Because the DateTime structure is not time zone-aware, you have to serialize both the DateTime value and the TimeZoneInfo object that represents its time zone. 创建同时包含其字段类型DateTime值和其所在的时区。Create a type whose fields include both the DateTime value and its time zone. 下面的示例定义DateWithTimeZone结构。The following example defines a DateWithTimeZone structure.

[!code-csharpSystem.DateTime.Persistence#6][!code-csharpSystem.DateTime.Persistence#6]

Namespace DateTimeExtensions
    <Serializable> Public Structure DateWithTimeZone
        Private tz As TimeZoneInfo
        Private dt As DateTime

        Public Sub New(dateValue As DateTime, timeZone As TimeZoneInfo)
            dt = dateValue
            tz = If(timeZone, TimeZoneInfo.Local)
        End Sub

        Public Property TimeZone As TimeZoneInfo
            Get
                Return tz
            End Get
            Set
                tz = Value
            End Set
        End Property

        Public Property DateTime As Date
            Get
                Return dt
            End Get
            Set
                dt = Value
            End Set
        End Property
    End Structure
End Namespace

重要

DateWithTimeZone接下来两个示例,该序列化和反序列化的数组中使用结构DateWithTimeZone对象。The DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. 您可以查看这篇文章的示例的整个集的源中任意一种Visual BasicC#从 GitHub 上的 docs 存储库。You can view the source for the entire set of examples from this article in either Visual Basic or C# from the docs repository on GitHub.

通过使用DateWithTimeZone结构,稍后可以保存日期和时间以及时区信息。By using the DateWithTimeZone structure, you can then persist date and time along with time zone information. 下面的示例使用BinaryFormatter类来序列化的数组DateWithTimeZone对象。The following example uses the BinaryFormatter class to serialize an array of DateWithTimeZone objects.

public static void SaveDateWithTimeZone()
{
    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")) };
    var fs = new FileStream(@".\Schedule.bin", FileMode.Create);
    var formatter = new BinaryFormatter();
    try
    {
        formatter.Serialize(fs, dates);
        // Display dates.
        foreach (var date in dates)
        {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine($"{date.DateTime} {(tz.IsDaylightSavingTime(date.DateTime) ? tz.DaylightName : tz.StandardName)}");
        }
    }
    catch (SerializationException e)
    {
        Console.WriteLine($"Serialization failed. Reason: {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
Public Sub SaveDateWithTimeZone()
    Dim dates As DateWithTimeZone() = {New DateWithTimeZone(#8/9/2014 7:30PM#,
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
                                  New DateWithTimeZone(#8/15/2014 7:00PM#,
                                      TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")),
                                  New DateWithTimeZone(#8/22/2014 7:30PM#,
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
                                  New DateWithTimeZone(#8/28/2014 7:00PM#,
                                      TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))}
    Dim fs As New FileStream(".\Schedule.bin", FileMode.Create)
    Dim formatter As New BinaryFormatter()
    Try
        formatter.Serialize(fs, dates)
    Catch e As SerializationException
        Console.WriteLine($"Serialization failed. Reason: {e.Message}")
    Finally
        If fs IsNot Nothing Then fs.Close()
    End Try
    ' Display dates.
    For Each dateInfo In dates
        Dim tz As TimeZoneInfo = dateInfo.TimeZone
        Console.WriteLine($"{dateInfo.DateTime} {If(tz.IsDaylightSavingTime(dateInfo.DateTime), tz.DaylightName, tz.StandardName)}")
    Next
End Sub
' 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

下面的示例然后调用BinaryFormatter.Deserialize方法来反序列化。The following example then calls the BinaryFormatter.Deserialize method to deserialize it.

public static void RestoreDateWithTimeZone()
{
    const string filename = @".\Schedule.bin";
    FileStream fs;
    if (File.Exists(filename))
        fs = new FileStream(filename, FileMode.Open);
    else
    {
        Console.WriteLine("Unable to find file to deserialize.");
        return;
    }

    var formatter = new BinaryFormatter();
    DateWithTimeZone[] dates;
    try
    {
        dates = (DateWithTimeZone[])formatter.Deserialize(fs);
        // Display dates.
        foreach (var date in dates)
        {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine($"{ date.DateTime} {(tz.IsDaylightSavingTime(date.DateTime) ? tz.DaylightName : tz.StandardName)}");
        }
    }
    catch (SerializationException e)
    {
        Console.WriteLine($"Deserialization failed. Reason: {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
Public Sub RestoreDateWithTimeZone()
    Dim fs As FileStream
    If File.Exists(filename) Then
        fs = New FileStream(filename, FileMode.Open)
    Else
        Console.WriteLine("Unable to find file to deserialize.")
        Exit Sub
    End If

    Dim formatter As New BinaryFormatter()
    Dim dates As DateWithTimeZone ()= Nothing
    Try
        dates = DirectCast(formatter.Deserialize(fs), DateWithTimeZone())
        ' Display dates.
        For Each dateInfo In dates
            Dim tz As TimeZoneInfo = dateInfo.TimeZone
            Console.WriteLine($"{dateInfo.DateTime} {If(tz.IsDaylightSavingTime(dateInfo.DateTime), tz.DaylightName, tz.StandardName)}")
        Next
    Catch e As SerializationException
        Console.WriteLine("Deserialization failed. Reason: {e.Message}")
    Finally
        If fs IsNot Nothing Then fs.Close()
    End Try
End Sub
' 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

DateTime vs。TimeSpanDateTime vs. TimeSpan

DateTimeTimeSpan的值类型的差异在于DateTime表示时间的某个时刻,而TimeSpan表示时间间隔。The DateTime and TimeSpan value types differ in that a DateTime represents an instant in time whereas a TimeSpan represents a time interval. 可以用的一个实例减去DateTime从另一个用来获取TimeSpan对象,表示它们之间的时间间隔。You can subtract one instance of DateTime from another to obtain a TimeSpan object that represents the time interval between them. 也可以添加一个值为正TimeSpan与当前DateTime若要获取DateTime值,该值表示将来的日期。Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date.

可以添加或减去的时间间隔从DateTime对象。You can add or subtract a time interval from a DateTime object. 时间间隔可以是负数或正数,并且它们可以表示以刻度为单位,例如单位秒,或作为TimeSpan对象。Time intervals can be negative or positive, and they can be expressed in units such as ticks, seconds, or as a TimeSpan object.

比较相等性的公差范围内Comparing for equality within tolerance

用于相等性比较DateTime确切的有效值。Equality comparisons for DateTime values are exact. 这意味着两个值必须表示为相同数量的计时周期将被视为相等。That means two values must be expressed as the same number of ticks to be considered equal. 该精度通常是不必要或甚至对于许多应用程序不正确。That precision is often unnecessary or even incorrect for many applications. 通常情况下,你想要测试是否DateTime对象是大致相等Often, you want to test if DateTime objects are roughly equal.

下面的示例演示如何比较大致等效DateTime值。The following example demonstrates how to compare roughly equivalent DateTime values. 声明它们相等时,它接受差异的一小块边距。It accepts a small margin of difference when declaring them equal.

[!code-csharpSystem.DateTime.Comparisons#1][!code-csharpSystem.DateTime.Comparisons#1]

Public Shared Function RoughlyEquals(time As DateTime, timeWithWindow As DateTime,
                             windowInSeconds As Integer,
                             frequencyInSeconds As Integer) As Boolean
    Dim delta As Long = (timeWithWindow.Subtract(time)).TotalSeconds _
                                            Mod frequencyInSeconds

    If delta > windowInSeconds Then
        delta = frequencyInSeconds - delta
    End If

    Return Math.Abs(delta) < windowInSeconds
End Function

Public Shared Sub TestRoughlyEquals()
    Dim window As Integer = 10
    Dim freq As Integer = 60 * 60 * 2 ' 2 hours;
    Dim d1 As DateTime = DateTime.Now

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

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

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

    Console.WriteLine($"d1 ({d1}) ~= d6 ({d6}): {RoughlyEquals(d1, d6, window, freq)}")
    Console.WriteLine($"d1 ({d1}) ~= d7 ({d7}): {RoughlyEquals(d1, d7, window, freq)}")
    Console.WriteLine($"d1 ({d1}) ~= d8 ({d8}): {RoughlyEquals(d1, d8, window, freq)}")
    Console.WriteLine($"d1 ({d1}) ~= d9 ({d9}): {RoughlyEquals(d1, d9, window, freq)}")
End Sub
' 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

COM 互操作注意事项COM interop considerations

一个DateTime值传输到 COM 应用程序,然后传输回托管应用程序,被认为是往返。A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. 但是,DateTime仅指定时间的值不往返正如您所料。However, a DateTime value that specifies only a time does not round-trip as you might expect.

如果您保存/还原仅时间,如下午 3 点、 最后一个日期和时间为公历公元 1899 年 12 月 30 日If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. 下午 3:00,而不是 1 月 1日日公元 0001 年at 3:00 P.M., instead of January, 1, 0001 C.E. 在下午 3:00at 3:00 P.M. .NET Framework 和 COM 假定默认日期时指定只在时间。The .NET Framework and COM assume a default date when only a time is specified. 但是,COM 系统假定公元,1899 年 12 月 30 日的基日期时.NET Framework 采用年 1 月 1 日公元 0001 年的基日期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.

当仅在时间从.NET Framework 传递到 COM 时,执行特殊处理,将时间转换为 com 使用的格式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. 当仅在时间从 COM 传递到.NET Framework 时,因为这会破坏合法的日期和时间或 1899 年 12 月 30 日之前不执行任何特殊处理。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. 如果日期从 COM 启动其往返,.NET Framework 和 COM 以保留日期。If a date starts its round-trip from COM, the .NET Framework and COM preserve the date.

.NET Framework 和 COM 的行为意味着,如果你的应用程序往返DateTime,仅指定一次,你的应用程序必须记得修改或忽略的错误的日期,从最后DateTime对象。The behavior of the .NET Framework and COM means that if your application round-trips a DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final DateTime object.

构造函数

DateTime(Int64) DateTime(Int64) DateTime(Int64) DateTime(Int64)

DateTime 结构的新实例初始化为指定的刻度数。Initializes a new instance of the DateTime structure to a specified number of ticks.

DateTime(Int64, DateTimeKind) DateTime(Int64, DateTimeKind) DateTime(Int64, DateTimeKind) DateTime(Int64, DateTimeKind)

DateTime 结构的新实例初始化为指定的计时周期数以及协调世界时 (UTC) 或本地时间。Initializes a new instance of the DateTime structure to a specified number of ticks and to Coordinated Universal Time (UTC) or local time.

DateTime(Int32, Int32, Int32) DateTime(Int32, Int32, Int32) DateTime(Int32, Int32, Int32) DateTime(Int32, Int32, Int32)

DateTime 结构的新实例初始化为指定的年、月和日。Initializes a new instance of the DateTime structure to the specified year, month, and day.

DateTime(Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Calendar)

DateTime 结构的新实例初始化为指定日历的指定年、月和日。Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar.

DateTime(Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32)

DateTime 结构的新实例初始化为指定的年、月、日、小时、分钟和秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second.

DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)

DateTime 结构的新实例初始化为指定年、月、日、小时、分钟、秒和协调世界时 (UTC) 或本地时间。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and Coordinated Universal Time (UTC) or local time.

DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar)

DateTime 结构的新实例初始化为指定日历的年、月、日、小时、分钟和秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second for the specified calendar.

DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32)

DateTime 结构的新实例初始化为指定的年、月、日、小时、分钟、秒和毫秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond.

DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)

DateTime 结构的新实例初始化为指定年、月、日、小时、分钟、秒、毫秒和协调世界时 (UTC) 或本地时间。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time.

DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar)

DateTime 结构的新实例初始化为指定日历的指定年、月、日、小时、分钟、秒和毫秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified calendar.

DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind)

DateTime 结构的新实例初始化为指定日历的指定年、月、日、小时、分钟、秒、毫秒和协调世界时 (UTC) 或本地时间。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.

字段

MaxValue MaxValue MaxValue MaxValue

表示 DateTime 的最大可能值。Represents the largest possible value of DateTime. 此字段为只读。This field is read-only.

MinValue MinValue MinValue MinValue

表示 DateTime 的最小可能值。Represents the smallest possible value of DateTime. 此字段为只读。This field is read-only.

UnixEpoch UnixEpoch UnixEpoch UnixEpoch

属性

Date Date Date Date

获取此实例的日期部分。Gets the date component of this instance.

Day Day Day Day

获取此实例所表示的日期为该月中的第几天。Gets the day of the month represented by this instance.

DayOfWeek DayOfWeek DayOfWeek DayOfWeek

获取此实例所表示的日期是星期几。Gets the day of the week represented by this instance.

DayOfYear DayOfYear DayOfYear DayOfYear

获取此实例所表示的日期是该年中的第几天。Gets the day of the year represented by this instance.

Hour Hour Hour Hour

获取此实例所表示日期的小时部分。Gets the hour component of the date represented by this instance.

Kind Kind Kind Kind

获取一个值,该值指示由此实例表示的时间是基于本地时间、协调世界时 (UTC),还是两者皆否。Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.

Millisecond Millisecond Millisecond Millisecond

获取此实例所表示日期的毫秒部分。Gets the milliseconds component of the date represented by this instance.

Minute Minute Minute Minute

获取此实例所表示日期的分钟部分。Gets the minute component of the date represented by this instance.

Month Month Month Month

获取此实例所表示日期的月份部分。Gets the month component of the date represented by this instance.

Now Now Now Now

获取一个 DateTime 对象,该对象设置为此计算机上的当前日期和时间,表示为本地时间。Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

Second Second Second Second

获取此实例所表示日期的秒部分。Gets the seconds component of the date represented by this instance.

Ticks Ticks Ticks Ticks

获取表示此实例的日期和时间的计时周期数。Gets the number of ticks that represent the date and time of this instance.

TimeOfDay TimeOfDay TimeOfDay TimeOfDay

获取此实例的当天的时间。Gets the time of day for this instance.

Today Today Today Today

获取当前日期。Gets the current date.

UtcNow UtcNow UtcNow UtcNow

获取一个 DateTime 对象,该对象设置为此计算机上的当前日期和时间,表示为协调通用时间 (UTC)。Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

Year Year Year Year

获取此实例所表示日期的年份部分。Gets the year component of the date represented by this instance.

方法

Add(TimeSpan) Add(TimeSpan) Add(TimeSpan) Add(TimeSpan)

返回一个新的 DateTime,它将指定 TimeSpan 的值添加到此实例的值上。Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

AddDays(Double) AddDays(Double) AddDays(Double) AddDays(Double)

返回一个新的 DateTime,它将指定的天数加到此实例的值上。Returns a new DateTime that adds the specified number of days to the value of this instance.

AddHours(Double) AddHours(Double) AddHours(Double) AddHours(Double)

返回一个新的 DateTime,它将指定的小时数加到此实例的值上。Returns a new DateTime that adds the specified number of hours to the value of this instance.

AddMilliseconds(Double) AddMilliseconds(Double) AddMilliseconds(Double) AddMilliseconds(Double)

返回一个新的 DateTime,它将指定的毫秒数加到此实例的值上。Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

AddMinutes(Double) AddMinutes(Double) AddMinutes(Double) AddMinutes(Double)

返回一个新的 DateTime,它将指定的分钟数加到此实例的值上。Returns a new DateTime that adds the specified number of minutes to the value of this instance.

AddMonths(Int32) AddMonths(Int32) AddMonths(Int32) AddMonths(Int32)

返回一个新的 DateTime,它将指定的月数加到此实例的值上。Returns a new DateTime that adds the specified number of months to the value of this instance.

AddSeconds(Double) AddSeconds(Double) AddSeconds(Double) AddSeconds(Double)

返回一个新的 DateTime,它将指定的秒数加到此实例的值上。Returns a new DateTime that adds the specified number of seconds to the value of this instance.

AddTicks(Int64) AddTicks(Int64) AddTicks(Int64) AddTicks(Int64)

返回一个新的 DateTime,它将指定的刻度数加到此实例的值上。Returns a new DateTime that adds the specified number of ticks to the value of this instance.

AddYears(Int32) AddYears(Int32) AddYears(Int32) AddYears(Int32)

返回一个新的 DateTime,它将指定的年份数加到此实例的值上。Returns a new DateTime that adds the specified number of years to the value of this instance.

Compare(DateTime, DateTime) Compare(DateTime, DateTime) Compare(DateTime, DateTime) Compare(DateTime, DateTime)

对两个 DateTime 的实例进行比较,并返回一个指示第一个实例是早于、等于还是晚于第二个实例的整数。Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

CompareTo(DateTime) CompareTo(DateTime) CompareTo(DateTime) CompareTo(DateTime)

将此实例的值与指定的 DateTime 值相比较,并返回一个整数,该整数指示此实例是早于、等于还是晚于指定的 DateTime 值。Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

CompareTo(Object) CompareTo(Object) CompareTo(Object) CompareTo(Object)

将此实例的值与包含指定的 DateTime 值的指定对象相比较,并返回一个整数,该整数指示此实例是早于、等于还是晚于指定的 DateTime 值。Compares the value of this instance to a specified object that contains a specified DateTime value, and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

DaysInMonth(Int32, Int32) DaysInMonth(Int32, Int32) DaysInMonth(Int32, Int32) DaysInMonth(Int32, Int32)

返回指定年和月中的天数。Returns the number of days in the specified month and year.

Equals(DateTime, DateTime) Equals(DateTime, DateTime) Equals(DateTime, DateTime) Equals(DateTime, DateTime)

返回一个值,该值指示的两个 DateTime 实例是否具有同一个日期和时间值。Returns a value indicating whether two DateTime instances have the same date and time value.

Equals(DateTime) Equals(DateTime) Equals(DateTime) Equals(DateTime)

返回一个值,该值指示此实例的值是否等于指定 DateTime 实例的值。Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

FromBinary(Int64) FromBinary(Int64) FromBinary(Int64) FromBinary(Int64)

反序列化一个 64 位二进制值,并重新创建序列化的 DateTime 初始对象。Deserializes a 64-bit binary value and recreates an original serialized DateTime object.

FromFileTime(Int64) FromFileTime(Int64) FromFileTime(Int64) FromFileTime(Int64)

将指定的 Windows 文件时间转换为等效的本地时间。Converts the specified Windows file time to an equivalent local time.

FromFileTimeUtc(Int64) FromFileTimeUtc(Int64) FromFileTimeUtc(Int64) FromFileTimeUtc(Int64)

将指定的 Windows 文件时间转换为等效的 UTC 时间。Converts the specified Windows file time to an equivalent UTC time.

FromOADate(Double) FromOADate(Double) FromOADate(Double) FromOADate(Double)

返回与指定的 OLE 自动化日期等效的 DateTimeReturns a DateTime equivalent to the specified OLE Automation Date.

GetDateTimeFormats() GetDateTimeFormats() GetDateTimeFormats() GetDateTimeFormats()

将此实例的值转换为标准日期和时间格式说明符支持的所有字符串表示形式。Converts the value of this instance to all the string representations supported by the standard date and time format specifiers.

GetDateTimeFormats(Char) GetDateTimeFormats(Char) GetDateTimeFormats(Char) GetDateTimeFormats(Char)

将此实例的值转换为指定的标准日期和时间格式说明符支持的所有字符串表示形式。Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier.

GetDateTimeFormats(IFormatProvider) GetDateTimeFormats(IFormatProvider) GetDateTimeFormats(IFormatProvider) GetDateTimeFormats(IFormatProvider)

将此实例的值转换为标准日期和时间格式说明符和指定的区域性特定格式信息支持的所有字符串表示形式。Converts the value of this instance to all the string representations supported by the standard date and time format specifiers and the specified culture-specific formatting information.

GetDateTimeFormats(Char, IFormatProvider) GetDateTimeFormats(Char, IFormatProvider) GetDateTimeFormats(Char, IFormatProvider) GetDateTimeFormats(Char, IFormatProvider)

将此实例的值转换为指定的标准日期和时间格式说明符和区域性特定格式信息支持的所有字符串表示形式。Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier and culture-specific formatting information.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

GetTypeCode() GetTypeCode() GetTypeCode() GetTypeCode()

返回值类型 TypeCodeDateTimeReturns the TypeCode for value type DateTime.

IsDaylightSavingTime() IsDaylightSavingTime() IsDaylightSavingTime() IsDaylightSavingTime()

指示此 DateTime 实例是否在当前时区的夏时制范围内。Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone.

IsLeapYear(Int32) IsLeapYear(Int32) IsLeapYear(Int32) IsLeapYear(Int32)

返回指定的年份是否为闰年的指示。Returns an indication whether the specified year is a leap year.

Parse(String) Parse(String) Parse(String) Parse(String)

使用当前线程区域性的约定将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using the conventions of the current thread culture.

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

使用指定的区域性特定格式设置信息,将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将包含日期和时间的字符串表示形式的内存范围转换为其等效的 DateTimeConverts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles) Parse(String, IFormatProvider, DateTimeStyles)

使用指定的区域性特定格式设置信息和格式类型,将日期和时间的字符串表示形式转换为其等效的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

ParseExact(String, String, IFormatProvider) ParseExact(String, String, IFormatProvider) ParseExact(String, String, IFormatProvider) ParseExact(String, String, IFormatProvider)

使用指定的格式和区域性特定格式信息,将日期和时间的指定字符串表示形式转换为其等效的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. 字符串表示形式的格式必须与指定的格式完全匹配。The format of the string representation must match the specified format exactly.

ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)
ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles) ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles) ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles) ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles)
ParseExact(String, String, IFormatProvider, DateTimeStyles) ParseExact(String, String, IFormatProvider, DateTimeStyles) ParseExact(String, String, IFormatProvider, DateTimeStyles) ParseExact(String, String, IFormatProvider, DateTimeStyles)

使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字符串表示形式的格式必须与指定的格式完全匹配,否则会引发异常。The format of the string representation must match the specified format exactly or an exception is thrown.

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

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字符串表示形式的格式必须至少与指定的格式之一完全匹配,否则会引发异常。The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

SpecifyKind(DateTime, DateTimeKind) SpecifyKind(DateTime, DateTimeKind) SpecifyKind(DateTime, DateTimeKind) SpecifyKind(DateTime, DateTimeKind)

创建新的 DateTime 对象,该对象具有与指定的 DateTime 相同的刻度数,但是根据指定的 DateTimeKind 值的指示,指定为本地时间或协调世界时 (UTC),或者两者皆否。Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.

Subtract(DateTime) Subtract(DateTime) Subtract(DateTime) Subtract(DateTime)

返回一个新的 DateTime,从此实例的值中减去指定的日期和时间。Returns a new DateTime that subtracts the specified date and time from the value of this instance.

Subtract(TimeSpan) Subtract(TimeSpan) Subtract(TimeSpan) Subtract(TimeSpan)

返回一个新的 DateTime,从此实例的值中减去指定持续时间。Returns a new DateTime that subtracts the specified duration from the value of this instance.

ToBinary() ToBinary() ToBinary() ToBinary()

将当前 DateTime 对象序列化为一个 64 位二进制值,该值随后可用于重新创建 DateTime 对象。Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object.

ToFileTime() ToFileTime() ToFileTime() ToFileTime()

将当前 DateTime 对象的值转换为 Windows 文件时间。Converts the value of the current DateTime object to a Windows file time.

ToFileTimeUtc() ToFileTimeUtc() ToFileTimeUtc() ToFileTimeUtc()

将当前 DateTime 对象的值转换为 Windows 文件时间。Converts the value of the current DateTime object to a Windows file time.

ToLocalTime() ToLocalTime() ToLocalTime() ToLocalTime()

将当前 DateTime 对象的值转换为本地时间。Converts the value of the current DateTime object to local time.

ToLongDateString() ToLongDateString() ToLongDateString() ToLongDateString()

将当前 DateTime 对象的值转换为其等效的长日期字符串表示形式。Converts the value of the current DateTime object to its equivalent long date string representation.

ToLongTimeString() ToLongTimeString() ToLongTimeString() ToLongTimeString()

将当前 DateTime 对象的值转换为其等效的长时间字符串表示形式。Converts the value of the current DateTime object to its equivalent long time string representation.

ToOADate() ToOADate() ToOADate() ToOADate()

将此实例的值转换为等效的 OLE 自动化日期。Converts the value of this instance to the equivalent OLE Automation date.

ToShortDateString() ToShortDateString() ToShortDateString() ToShortDateString()

将当前 DateTime 对象的值转换为其等效的短日期字符串表示形式。Converts the value of the current DateTime object to its equivalent short date string representation.

ToShortTimeString() ToShortTimeString() ToShortTimeString() ToShortTimeString()

将当前 DateTime 对象的值转换为其等效的短时间字符串表示形式。Converts the value of the current DateTime object to its equivalent short time string representation.

ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider)

使用指定的格式和区域性特定格式信息将当前 DateTime 对象的值转换为它的等效字符串表示形式。Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.

ToString(String) ToString(String) ToString(String) ToString(String)

使用指定的格式和当前区域性的格式约定将当前 DateTime 对象的值转换为它的等效字符串表示形式。Converts the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture.

ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider)

使用指定的区域性特定格式信息将当前 DateTime 对象的值转换为它的等效字符串表示形式。Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information.

ToString() ToString() ToString() ToString()

使用当前的区域性格式约定将当前 DateTime 对象的值转换为它的等效字符串表示形式。Converts the value of the current DateTime object to its equivalent string representation using the formatting conventions of the current culture.

ToUniversalTime() ToUniversalTime() ToUniversalTime() ToUniversalTime()

将当前 DateTime 对象的值转换为协调世界时 (UTC)。Converts the value of the current DateTime object to Coordinated Universal Time (UTC).

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)
TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)
TryParse(String, DateTime) TryParse(String, DateTime) TryParse(String, DateTime) TryParse(String, DateTime)

将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的区域性特定格式信息和格式设置样式,将日期和时间的指定字符串表示形式转换为其 DateTime 等效项,并返回一个指示转换是否成功的值。Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime) TryParse(ReadOnlySpan<Char>, DateTime)
TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)
TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles, DateTime) TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles, DateTime)
TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、区域性特定的格式信息和样式将日期和时间的指定字符串表示形式转换为其等效的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字符串表示形式的格式必须与指定的格式完全匹配。The format of the string representation must match the specified format exactly. 该方法返回一个指示转换是否成功的值。The method returns a value that indicates whether the conversion succeeded.

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

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字符串表示形式的格式必须至少与指定的格式之一完全匹配。The format of the string representation must match at least one of the specified formats exactly. 该方法返回一个指示转换是否成功的值。The method returns a value that indicates whether the conversion succeeded.

操作员

Addition(DateTime, TimeSpan) Addition(DateTime, TimeSpan) Addition(DateTime, TimeSpan) Addition(DateTime, TimeSpan)

将指定的时间间隔加到指定的日期和时间以生成新的日期和时间。Adds a specified time interval to a specified date and time, yielding a new date and time.

Equality(DateTime, DateTime) Equality(DateTime, DateTime) Equality(DateTime, DateTime) Equality(DateTime, DateTime)

确定 DateTime 的两个指定的实例是否相等。Determines whether two specified instances of DateTime are equal.

GreaterThan(DateTime, DateTime) GreaterThan(DateTime, DateTime) GreaterThan(DateTime, DateTime) GreaterThan(DateTime, DateTime)

确定指定的 DateTime 是否晚于另一个指定的 DateTimeDetermines whether one specified DateTime is later than another specified DateTime.

GreaterThanOrEqual(DateTime, DateTime) GreaterThanOrEqual(DateTime, DateTime) GreaterThanOrEqual(DateTime, DateTime) GreaterThanOrEqual(DateTime, DateTime)

确定一个指定的 DateTime 表示的日期和时间等于还是晚于另一个指定的 DateTimeDetermines whether one specified DateTime represents a date and time that is the same as or later than another specified DateTime.

Inequality(DateTime, DateTime) Inequality(DateTime, DateTime) Inequality(DateTime, DateTime) Inequality(DateTime, DateTime)

确定 DateTime 的两个指定的实例是否不等。Determines whether two specified instances of DateTime are not equal.

LessThan(DateTime, DateTime) LessThan(DateTime, DateTime) LessThan(DateTime, DateTime) LessThan(DateTime, DateTime)

确定指定的 DateTime 是否早于另一个指定的 DateTimeDetermines whether one specified DateTime is earlier than another specified DateTime.

LessThanOrEqual(DateTime, DateTime) LessThanOrEqual(DateTime, DateTime) LessThanOrEqual(DateTime, DateTime) LessThanOrEqual(DateTime, DateTime)

确定一个指定的 DateTime 表示的日期和时间等于还是早于另一个指定的 DateTimeDetermines whether one specified DateTime represents a date and time that is the same as or earlier than another specified DateTime.

Subtraction(DateTime, TimeSpan) Subtraction(DateTime, TimeSpan) Subtraction(DateTime, TimeSpan) Subtraction(DateTime, TimeSpan)

从指定的日期和时间减去指定的时间间隔,返回新的日期和时间。Subtracts a specified time interval from a specified date and time and returns a new date and time.

Subtraction(DateTime, DateTime) Subtraction(DateTime, DateTime) Subtraction(DateTime, DateTime) Subtraction(DateTime, DateTime)

将指定的日期和时间与另一个指定的日期和时间相减,返回一个时间间隔。Subtracts a specified date and time from another specified date and time and returns a time interval.

显式界面实现

IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object)
IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode()
IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider)

返回当前 DateTime 对象。Returns the current DateTime object.

IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider)

将当前 DateTime 对象转换为指定类型的对象。Converts the current DateTime object to an object of a specified type.

IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用序列化当前的 SerializationInfo 对象所需的所有数据填充 DateTime 对象。Populates a SerializationInfo object with the data needed to serialize the current DateTime object.

适用于

线程安全性

此类型所有成员都是线程安全。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.

另请参阅