DateTime 结构

定义

表示时间上的一刻,通常以日期和当天的时间表示。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
继承
DateTime
属性
实现

注解

重要

日本历法中的年号是根据天皇统治来命名的,因此预计会发生变化。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.

本文包括使用 @no__t 类型的几个示例: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:

@No__t 值类型表示日期和时间,其值范围为00:00:00 (午夜),0001年1月1日至年1月1日下午11:59:59,年12月31日,9999公元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.) in the Gregorian calendar.

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

备注

如果使用的计时周期值要转换为其他时间间隔(如分钟或秒),则应使用 TimeSpan.TicksPerDayTimeSpan.TicksPerHourTimeSpan.TicksPerMinuteTimeSpan.TicksPerSecond 或 @no__t 的常量来执行转换。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. 例如,若要将指定的刻度数表示的秒数加到 DateTime 值的 @no__t,则可以使用表达式 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 上的文档存储库中查看本文的整个示例集源。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 结构的一种替代方法是 @no__t 的结构。An alternative to the DateTime structure for working with date and time values in particular time zones is the DateTimeOffset structure. @No__t-0 结构将日期和时间信息存储在私有 DateTime 字段中,以及日期和时间与 UTC 在专用 @no__t 2 字段中不同的分钟数。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. 这样,@no__t 0 值就可以反映特定时区中的时间,而 @no__t 1 值就只能明确反映 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. 有关在处理日期和时间值时何时使用 @no__t 0 结构或 DateTimeOffset 结构的讨论,请参阅在DateTime、DateTimeOffset、TimeSpan 和 TimeZoneInfo 之间进行选择For 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 parameterless constructor.
  • 将 @no__t 0 赋给属性或方法的返回值。Assigning a DateTime to the return value of a property or method.
  • 正在从其字符串表示形式分析 @no__t 值0。Parsing a DateTime value from its string representation.
  • 使用 Visual Basic 特定语言功能来实例化 @no__t。Using 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);

当你希望 @no__t 初始化为其默认值时,可以调用 DateTime 结构的隐式无参数构造函数。You invoke the DateTime structure's implicit parameterless constructor when you want a DateTime initialized to its default value. (有关值类型的隐式无参数构造函数的详细信息,请参阅值类型。)某些编译器还支持声明 @no__t 值0值,而无需向其显式赋值。(For details on the implicit parameterless 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. 下面的示例演示了和 Visual Basic 中C#的 @no__t 0 隐式无参数构造函数,以及 Visual Basic 中无赋值的 @no__t 2 声明。The following example illustrates the DateTime implicit parameterless 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

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

@No__t,ParseExactTryParse 和 @no__t 3 方法均将字符串转换为其等效的日期和时间值。The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. 下面的示例使用 @no__t 0 和 ParseExact 方法来分析字符串并将其转换为 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);

@No__t-0 和 TryParseExact 方法指示字符串是否为 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 语句初始化新的 @no__t 0 值。The following Visual Basic statement initializes a new DateTime value.

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

DateTime 值及其字符串表示形式DateTime values and their string representations

在内部,所有 @no__t 0 值都表示为自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. 实际 @no__t 0 值与显示时值的显示方式无关。The actual DateTime value is independent of the way in which that value appears when displayed. @No__t-0 值的外观是格式设置操作的结果,该操作将值转换为其字符串表示形式。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. @No__t-0 结构通过 ToString 的重载为日期和时间值设置格式提供灵活性。The 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. @No__t-0 方法使用当前区域性的格式设置约定返回由标准或自定义格式说明符定义的字符串表示形式。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

@No__t-0 重载还可与自定义格式字符串一起用于指定其他格式。The DateTime.ToString(String) overload can also be used with a custom format string to specify other formats. 下面的示例演示如何使用通常用于 web 服务的ISO 8601标准格式来设置字符串的格式。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

分析将日期和时间的字符串表示形式转换为 @no__t 的值。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 的用户将日期值输入为 "12/15/2013" 或 "12 月15日,2013"。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 的用户将日期值输入为 "15/12/2013" 或 "15 12 月12日 2013"。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.

使用 @no__t 0 或 TryParse 方法可将字符串从区域性使用的通用日期和时间格式之一转换为 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 将不同区域性特定格式的日期字符串转换为 @no__t 1 值。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

使用 @no__t 0 和 TryParseExact 方法将必须与特定格式或格式匹配的字符串转换为 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

@No__t-0 的一个常见用途是转换 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}")

如果无法分析字符串,@no__t 0 和 ParseExact 方法将引发异常。If a string cannot be parsed, the Parse and ParseExact methods throw an exception. @No__t,TryParseExact 方法返回一个 Boolean 值,该值指示转换是成功还是失败。The TryParse and TryParseExact methods return a Boolean value that indicates whether the conversion succeeded or failed. 在性能非常重要的方案中,应使用 @no__t 0 或 @no__t 方法。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 值DateTime values

通常使用协调世界时(UTC)标准来表示 DateTime 类型中的时间值说明。Descriptions of time values in the DateTime type are often expressed using the Coordinated Universal Time (UTC) standard. 协调世界时是格林尼治标准时间(GMT)的国际识别的名称。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.

如果 @no__t 对象的 Kind 属性为 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 值执行日期和时间算法以测量运行时间的替代方法,可以使用 @no__t 类。As an alternative to performing date and time arithmetic on DateTime values to measure elapsed time, you can use the Stopwatch class.

@No__t-0 属性表示日期和时间值,单位为 1 10-秒秒。The Ticks property expresses date and time values in units of one ten-millionth of a second. @No__t-0 属性返回日期和时间值的千分之几秒。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 方法会导致5毫秒的延迟。If the value of the outer loop counter is 10, a call to the Thread.Sleep method introduces a five-millisecond delay. 下面的示例显示了在对 Thread.Sleep 进行调用之后 DateTime.Now.Milliseconds 属性更改所返回的毫秒数。The 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

使用 @no__t 的结构,如 @no__t 或 Subtract)的计算不会修改该结构的值。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.

@No__t-0 结构本身为从一个时区转换到另一个时区提供有限支持。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.

仅当对象表示相同时区中的时间时,@no__t 的对象的计算和比较才有意义。Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the same time zone. 您可以使用 @no__t 0 对象来表示 @no__t 1 值的时区,尽管这两个值是松散耦合的。You can use a TimeZoneInfo object to represent a DateTime value's time zone, although the two are loosely coupled. @No__t-0 对象没有返回对象的属性,该对象表示日期和时间值的时区。A DateTime object does not have a property that returns an object that represents that date and time value's time zone. @No__t-0 属性指示 DateTime 表示 UTC、本地时间还是未指定。The Kind property indicates if a DateTime represents UTC, local time, or is unspecified. 在时区感知应用程序中,必须依赖于某些外部机制来确定创建 @no__t 0 对象的时区。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 值和表示 DateTime 值时区的 @no__t 对象的结构。You could use a structure that wraps both the DateTime value and the TimeZoneInfo object that represents the DateTime value's time zone. 若要详细了解如何在计算中使用 UTC 和 DateTime 值进行比较,请参阅使用日期和时间执行算术运算For details on using UTC in calculations and comparisons with DateTime values, see Performing Arithmetic Operations with Dates and Times.

每个 @no__t 0 成员将隐式使用公历来执行其操作。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.

@No__t 类型的成员执行的操作将考虑闰年和一个月中的天数等详细信息。Operations by members of the DateTime type take into account details such as leap years and the number of days in a month.

DateTime 值和日历DateTime values and calendars

.NET Framework 类库包含许多 calendar 类,它们都派生自 @no__t 0 类。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 对象当前使用的日历由其 @no__t 属性定义。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. 如果在日期和时间格式设置操作中使用表示泰国历区域性的 @no__t 0 对象,则默认情况下使用泰国历年代日历。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. 公历仅在区域性的 @no__t 0 属性更改时使用,如下面的示例所示: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

您可以使用日期和时间元素(年、月和日)来实例化一个 @no__t 的值,方法是调用包含 calendar 参数的DateTime 构造函数并向其传递一个表示该日历的 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. 下面的示例使用 @no__t 日历中的日期和时间元素。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

不包含 calendar 参数 @no__t 0 构造函数假设日期和时间元素以公历表示为单位。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) 方法假设 @no__t 公历中的年份为一年。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. 使用公历的每个 @no__t 0 成员都具有使用特定日历的 @no__t 1 类的相应成员。Each DateTime member that uses the Gregorian calendar has a corresponding member of the Calendar class that uses a specific calendar. 例如,@no__t 0 方法返回特定日历中的年份,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. 下面的示例同时使用 @no__t 0 和 @no__t 类的相应成员。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

@No__t-0 结构包含一个 @no__t 属性,该属性返回公历中的第几天。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. 若要检索一年中的某一周,请调用单个日历的 @no__t 0 方法。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

可以通过以下四种方式持久保存 @no__t 值:You can persist DateTime values in four ways:

无论选择哪种方法,都必须确保还原 @no__t 值的例程不会丢失数据或引发异常。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

若要成功还原作为字符串保存的 @no__t 0 值,请遵循以下规则:To successfully restore DateTime values that are persisted as strings, follow these rules:

  • 当你在还原字符串时将其视为保留时,请对区域性特定的格式设置相同的假设。Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. 若要确保可在其当前区域性不同于其保存所在系统的区域性的系统上还原字符串,请使用固定区域性的约定调用 @no__t 0 重载来保存字符串。To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the ToString overload to save the string by using the conventions of the invariant culture. 使用固定区域性的约定调用 @no__t 0 或 TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 重载来还原字符串。Call the Parse(String, IFormatProvider, DateTimeStyles) or TryParse(String, IFormatProvider, DateTimeStyles, DateTime) overload to restore the string by using the conventions of the invariant culture. 永远不要使用 ToString()Parse(String)TryParse(String, DateTime) 重载,它们使用当前线程区域性的约定。Never use the ToString(), Parse(String), or TryParse(String, DateTime) overloads, which use the conventions of the current thread culture.

  • 如果该日期表示一个时间点,请确保它在还原时表示相同的时间点,即使在不同的时区也是如此。If the date represents a single moment of time, ensure that it represents the same moment in time when it's restored, even on a different time zone. 保存之前,将 DateTime 值转换为协调世界时(UTC)。Convert the DateTime value to Coordinated Universal Time (UTC) before saving it. 你还可以将值和时区信息进行序列化。You can also serialize the value along with time zone information. 有关此方法的详细信息,请参阅序列化日期时间和时区数据For more information about this approach, see Serializing DateTime and time zone data.

将 @no__t 值作为字符串保留时,最常见的错误是依赖于默认或当前区域性的格式设置约定。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...

若要成功往返 @no__t 值为0的值,请执行以下步骤:To round-trip DateTime values successfully, follow these steps:

  1. 如果这些值表示一段时间,则通过调用 @no__t 0 方法将它们从本地时间转换为 UTC。If the values represent single moments of time, convert them from the local time to UTC by calling the ToUniversalTime method.
  2. 通过调用 @no__t 0 或 @no__t 1 重载,将日期转换为其字符串表示形式。Convert the dates to their string representations by calling the ToString(String, IFormatProvider) or String.Format(IFormatProvider, String, Object[]) overload. 通过指定 @no__t 为 @no__t 1 参数,使用固定区域性的格式设置约定。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.

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

  1. 通过调用 @no__t 0 或 TryParseExact 重载来分析数据。Parse the data by calling the ParseExact or TryParseExact overload. 指定 CultureInfo.InvariantCulture 作为 @no__t 参数,并使用在转换过程中用于 format 参数的相同标准格式字符串。Specify CultureInfo.InvariantCulture as the provider argument, and use the same standard format string you used for the format argument during conversion. 在 @no__t 参数中包含 DateTimeStyles.RoundtripKind 值。Include the DateTimeStyles.RoundtripKind value in the styles argument.
  2. 如果 @no__t 0 值表示一段时间,则调用 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" 标准格式字符串,以确保无论源和目标系统的系统、区域性或时区如何,已保存和还原 @no__t 0 值都表示同一时刻。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

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

若要将 @no__t 0 值作为整数保存:To persist a DateTime value as an integer:

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

若要还原已持久化为整数的 @no__t 0 值:To restore a DateTime value that has been persisted as an integer:

  1. 通过将 Int64 值传递到第 2 @no__t 构造函数来实例化新的 DateTime 对象。Instantiate a new DateTime object by passing the Int64 value to the DateTime(Int64) constructor.
  2. 如果 @no__t 0 值表示单个时间点,请通过调用 ToLocalTime 方法将其从 UTC 转换为本地时间。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 值,该值指示紧随其后的 @no__t 1 值的总数。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

可以通过序列化将 @no__t 值保留到流或文件中,然后通过反序列化来还原它们。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 类对 @no__t 1 值进行序列化和反序列化。The following example uses the XmlSerializer class to serialize and deserialize DateTime values. 这些值表示二十个世纪内的所有闰年。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). 由于已经反序列化 @no__t 0 对象本身,因此代码不必处理日期和时间格式的区域性差异。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. 如果 @no__t 0 值表示时间点,并表示为本地时间,请通过调用 ToUniversalTime 方法将其从本地时间转换为 UTC,然后将其从本地时间转换为 UTC。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. 反序列化后,通过调用 @no__t 0 方法将其从 UTC 转换为本地时间。After you deserialize it, convert it from UTC to local time by calling the ToLocalTime method. 下面的示例使用 BinaryFormatter 类在美国的系统中对系统上的 @no__t 数据进行序列化太平洋标准时区并在美国英语系统中对其进行反序列化中部标准区域。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

前面的示例假定 @no__t 0 值表示为本地时间。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 结构不能识别时区,因此您必须序列化 @no__t 1 值和表示其时区的 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. 创建一个类型,其字段同时包括 @no__t 值和时区。Create a type whose fields include both the DateTime value and its time zone. 下面的示例定义了一个 @no__t 的结构。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 结构来序列化和反序列化 @no__t 一组对象。The DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. 可以在Visual BasicC# GitHub 上的文档存储库中查看本文的整个示例集源。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 类对 @no__t 对象的数组进行序列化。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 与TimeSpanDateTime vs. TimeSpan

@No__t @no__t 值类型不同,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,以获取表示二者之间时间间隔的 @no__t 1 对象。You can subtract one instance of DateTime from another to obtain a TimeSpan object that represents the time interval between them. 或者,您可以向当前 @no__t 添加正 @no__t 0,以获取一个表示未来日期的 @no__t 2 值。Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date.

可以添加或减去 @no__t 0 对象中的时间间隔。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

@No__t 值的相等比较是精确的。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. 通常,你需要测试 @no__t 0 对象是否大致相等Often, you want to test if DateTime objects are roughly equal.

下面的示例演示如何比较大致等效的 @no__t 0 值。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

传输到 COM 应用程序的 @no__t 0 值,然后将其传输回托管应用程序,这称为往返。A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. 不过,@no__t 值为0,则仅指定时间不会像预期那样往返。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,而不是公元0001年1月1日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 假设基准日期为公元0001年1月1日。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 的行为意味着,如果应用程序往返 @no__t 仅指定时间的-0,则应用程序必须记得修改或忽略最终 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(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 结构的新实例初始化为指定日历的指定年、月和日。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 结构的新实例初始化为指定的年、月、日、小时、分钟和秒。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, 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, 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, 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, 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 结构的新实例初始化为指定日历的指定年、月、日、小时、分钟、秒、毫秒和协调世界时 (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.

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(Int64)

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

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.

字段

MaxValue

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

MinValue

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

UnixEpoch

属性

Date

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

Day

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

DayOfWeek

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

DayOfYear

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

Hour

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

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

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

Minute

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

Month

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

Now

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

Second

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

Ticks

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

TimeOfDay

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

Today

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

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

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

方法

Add(TimeSpan)

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

AddDays(Double)

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

AddHours(Double)

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

AddMilliseconds(Double)

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

AddMinutes(Double)

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

AddMonths(Int32)

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

AddSeconds(Double)

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

AddTicks(Int64)

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

AddYears(Int32)

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

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)

将此实例的值与指定的 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)

将此实例的值与包含指定的 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)

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

Equals(DateTime)

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

Equals(DateTime, DateTime)

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

Equals(Object)

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

FromBinary(Int64)

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

FromFileTime(Int64)

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

FromFileTimeUtc(Int64)

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

FromOADate(Double)

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

GetDateTimeFormats()

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

GetDateTimeFormats(Char)

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

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.

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.

GetHashCode()

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

GetTypeCode()

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

IsDaylightSavingTime()

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

IsLeapYear(Int32)

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

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)

使用当前线程区域性的约定将日期和时间的字符串表示形式转换为其等效的 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)

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

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(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)
ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles)
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(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)

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 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)

创建新的 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)

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

Subtract(TimeSpan)

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

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()

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

ToFileTimeUtc()

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

ToLocalTime()

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

ToLongDateString()

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

ToLongTimeString()

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

ToOADate()

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

ToShortDateString()

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

ToShortTimeString()

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

ToString()

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

ToString(IFormatProvider)

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

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(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.

ToUniversalTime()

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

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)
TryParse(ReadOnlySpan<Char>, DateTime)
TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, 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)

使用指定的区域性特定格式信息和格式设置样式,将日期和时间的指定字符串表示形式转换为其 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.

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)
TryParseExact(ReadOnlySpan<Char>, 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)

使用指定的格式数组、区域性特定格式信息和样式,将日期和时间的指定字符串表示形式转换为其等效的 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)

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

Equality(DateTime, DateTime)

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

GreaterThan(DateTime, DateTime)

确定指定的 DateTime 是否晚于另一个指定的 DateTimeDetermines whether one specified DateTime is later than another specified 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)

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

LessThan(DateTime, DateTime)

确定指定的 DateTime 是否早于另一个指定的 DateTimeDetermines whether one specified DateTime is earlier than another specified 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, DateTime)

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

Subtraction(DateTime, TimeSpan)

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

显式界面实现

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

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

IConvertible.ToByte(IFormatProvider)

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

IConvertible.ToChar(IFormatProvider)

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

IConvertible.ToDateTime(IFormatProvider)

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

IConvertible.ToDecimal(IFormatProvider)

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

IConvertible.ToDouble(IFormatProvider)

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

IConvertible.ToInt16(IFormatProvider)

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

IConvertible.ToInt32(IFormatProvider)

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

IConvertible.ToInt64(IFormatProvider)

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

IConvertible.ToSByte(IFormatProvider)

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

IConvertible.ToSingle(IFormatProvider)

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

IConvertible.ToType(Type, IFormatProvider)

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

IConvertible.ToUInt16(IFormatProvider)

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

IConvertible.ToUInt32(IFormatProvider)

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

IConvertible.ToUInt64(IFormatProvider)

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

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.

另请参阅