DateTime DateTime DateTime DateTime Struct

定義

表示時間的瞬間,通常以一天的日期和時間表示。Represents an instant in time, typically expressed as a date and time of day.

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

備註

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 此變更對使用這些日曆的所有應用程式都有影響。Such a change of era affects all applications that use these calendars. 若要取得詳細資訊及判斷您的應用程式是否受影響,請參閱 Handling a new era in the Japanese calendar in .NET (處理 .NET 中日本日曆的新紀元)。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 若要了解如何在 Windows 系統上測試您的應用程式,確保其已準備好面對紀元變更,請參閱 Prepare your application for the Japanese era change (讓應用程式準備好因應日本紀元變更)。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 內嵌程式碼執行器與 Playground 的當地時區是全球標準時間 (UTC)。The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. 這可能會影響示範 DateTimeDateTimeOffsetTimeZoneInfo 型別與其成員之範例的行為與輸出。This may affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.

本文包含幾個使用 DateTime 類型的範例:This article includes several examples that use the DateTime type:

初始化範例Initialization Examples

DateTime 物件格式化為字串Formatting DateTime objects as strings

將字串剖析為 @no__t 1 個物件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-0 數值型別代表日期和時間,其值範圍介於00:00:00 (午夜)、0001年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. 特定日期是自西元0001年1月1日午夜12:00 起的刻度數目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 的刻度值代表 12:00:00 0100 年1月01日星期五午夜的日期。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.TicksPerSecondTimeSpan.TicksPerMillisecond 常數來執行轉換。If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the TimeSpan.TicksPerDay, TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.TicksPerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. 例如,若要將指定之刻度數所表示的秒數加上 DateTime 值的 Second 元件,您可以使用運算式 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 結構的替代方法是 DateTimeOffset 結構。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 欄位中,以及日期和時間與私用 Int16 欄位中的 UTC 不同的分鐘數。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. 如需在處理日期和時間值時,使用 DateTime 結構或 @no__t 1 結構的討論,請參閱在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

您可以透過許多不同的方式,將初始值指派給新的 @no__t 0 值: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.
  • DateTime 指派給屬性或方法的傳回值。Assigning a DateTime to the return value of a property or method.
  • 從字串標記法剖析 DateTime 值。Parsing a DateTime value from its string representation.
  • 使用 Visual Basic 特定的語言功能來具現化 DateTimeUsing Visual Basic-specific language features to instantiate a DateTime.

下列程式碼片段會顯示每個的範例:The following code snippets show examples of each:

叫用析構函式Invoke Constructors

您可以呼叫 DateTime 的任何多載,以指定日期和時間值的元素(例如年、月、日或刻度數目)。You call any of the overloads of the DateTime constructor that specify elements of the date and time value (such as the year, month, and day, or the number of ticks). 下列程式碼會使用指定年、月、日、小時、分鐘和秒的 DateTime 的函式來建立特定日期。The following code creates a specific date using the DateTime constructor specifying the year, month, day, hour, minute, and second.

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

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

當您想要將 DateTime 初始化為預設值時,您可以叫用 DateTime 結構的隱含無參數函式。You invoke the DateTime structure's implicit 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

您可以為 DateTime 物件指派屬性或方法所傳回的日期和時間值。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-0、ParseExactTryParse 和 @no__t 3 方法全都會將字串轉換為其相等的日期和時間值。The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. 下列範例會使用 ParseParseExact 方法來剖析字串,並將它轉換成 @no__t 2 值。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 和 @no__t 1 方法會指出字串是否為 @no__t 2 值的有效表示,如果是,則會執行轉換。The TryParse and TryParseExact methods indicate whether a string is a valid representation of a DateTime value and, if it is, performs the conversion.

Visual Basic 的語言特定語法Language-specific syntax for Visual Basic

下列 Visual Basic 語句會初始化新的 DateTime 值。The following Visual Basic statement initializes a new DateTime value.

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

日期時間值及其字串表示DateTime values and their string representations

就內部而言,所有 @no__t 0 值都會表示為12:00:00 從0001年1月1日午夜起經過的刻度數(100-毫微秒間隔)。Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. 實際的 DateTime 值與顯示時顯示該值的方式無關。The actual DateTime value is independent of the way in which that value appears when displayed. @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 0 的值。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-gb 的使用者輸入日期值為 "15/12/2013" 或 "15 十二月 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.

您可以使用 ParseTryParse 方法,將字串從文化特性使用的其中一個通用日期和時間格式轉換為 @no__t 2 值。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

您可以使用 ParseExactTryParseExact 方法,將必須符合特定格式或格式的字串轉換為 @no__t 2 值。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}")

如果無法剖析字串,Parse 和 @no__t 1 方法會擲回例外狀況。If a string cannot be parsed, the Parse and ParseExact methods throw an exception. @No__t-0 和 @no__t 1 方法會傳回表示轉換是否成功或失敗的 @no__t 2 值。The TryParse and TryParseExact methods return a Boolean value that indicates whether the conversion succeeded or failed. 在效能很重要的案例中,您應該使用 TryParse 或 @no__t 1 方法。You should use the TryParse or TryParseExact methods in scenarios where performance is important. 日期和時間字串的剖析作業通常會有較高的失敗率,而例外狀況處理則很昂貴。The parsing operation for date and time strings tends to have a high failure rate, and exception handling is expensive. 如果是由使用者輸入或來自不明來源的字串,請使用這些方法。Use these methods if strings are input by users or coming from an unknown source.

如需剖析日期和時間值的詳細資訊,請參閱剖析日期和時間字串For more information about parsing date and time values, see Parsing Date and Time Strings.

日期時間值DateTime values

@No__t 0 類型中的時間值描述通常會使用國際標準時間(UTC)標準來表示。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.

如果 DateTime 物件的 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

注意

除了在 @no__t 0 值上執行日期和時間運算來測量已耗用時間的替代方法,您可以使用 Stopwatch 類別。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 方法會引進五毫秒的延遲。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 operations

使用 DateTime 結構的計算(例如 AddSubtract)不會修改結構的值。A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. 相反地,計算會傳回新的 DateTime 結構,其值為計算的結果。Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.

時間區域之間的轉換作業(例如,UTC 和本地時間之間,或在一個時區與另一個區域之間)會將日光節約時間納入考慮,但算術和比較作業則不會。Conversion operations between time zones (such as between UTC and local time, or between one time zone and another) take daylight saving time into account, but arithmetic and comparison operations do not.

@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 0 物件的計算和比較才有意義。Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the same time zone. 您可以使用 TimeZoneInfo 物件來代表 @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 值的結構,以及代表 @no__t 2 值時區的 TimeZoneInfo 物件。You could use a structure that wraps both the DateTime value and the TimeZoneInfo object that represents the DateTime value's time zone. 如需在計算和與 @no__t 0 值的比較中使用 UTC 的詳細資訊,請參閱使用日期和時間執行算數運算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.

DateTime 類型成員所進行的作業會將詳細資料(例如閏年)和月中的天數納入考慮。Operations by members of the DateTime type take into account details such as leap years and the number of days in a month.

日期時間值和行事曆DateTime values and calendars

.NET Framework 類別庫包含許多行事曆類別,全都是從 Calendar 類別衍生而來。The .NET Framework Class Library includes a number of calendar classes, all of which are derived from the Calendar class. 包括:They are:

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 此變更對使用這些日曆的所有應用程式都有影響。Such a change of era affects all applications that use these calendars. 若要取得詳細資訊及判斷您的應用程式是否受影響,請參閱 Handling a new era in the Japanese calendar in .NET (處理 .NET 中日本日曆的新紀元)。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 若要了解如何在 Windows 系統上測試您的應用程式,確保其已準備好面對紀元變更,請參閱 Prepare your application for the Japanese era change (讓應用程式準備好因應日本紀元變更)。See Prepare your application for the Japanese era change for information on testing your applications on Windows systems to ensure their readiness for the era change. 請參閱使用紀年以了解 .NET 中支援使用多種紀年的日曆,以及在處理支援多種紀年的日曆時能採用最佳做法。See Working with eras for features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras.

每個文化特性都會使用其唯讀 CultureInfo.Calendar 屬性所定義的預設行事曆。Each culture uses a default calendar defined by its read-only CultureInfo.Calendar property. 每個文化特性都可支援其唯讀 CultureInfo.OptionalCalendars 屬性所定義的一或多個行事曆。Each culture may support one or more calendars defined by its read-only CultureInfo.OptionalCalendars property. 特定 CultureInfo 物件目前使用的行事曆是由其 DateTimeFormatInfo.Calendar 屬性所定義。The calendar currently used by a specific CultureInfo object is defined by its DateTimeFormatInfo.Calendar property. 它必須是在 CultureInfo.OptionalCalendars 陣列中找到的其中一個行事曆。It must be one of the calendars found in the CultureInfo.OptionalCalendars array.

文化特性的目前行事曆用於該文化特性的所有格式化作業。A culture's current calendar is used in all formatting operations for that culture. 例如,泰文泰文化特性的預設行事曆是泰文曆紀元行事曆,以 ThaiBuddhistCalendar 類別表示。For example, the default calendar of the Thai Buddhist culture is the Thai Buddhist Era calendar, which is represented by the ThaiBuddhistCalendar class. 當日期和時間格式作業中使用代表泰文泰文化特性的 CultureInfo 物件時,預設會使用泰文泰年代行事曆。When a CultureInfo object that represents the Thai Buddhist culture is used in a date and time formatting operation, the Thai Buddhist Era calendar is used by default. 只有當文化特性的 DateTimeFormatInfo.Calendar 屬性變更時,才會使用西曆,如下列範例所示:The Gregorian calendar is used only if the culture's DateTimeFormatInfo.Calendar property is changed, as the following example shows:

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

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

Console.WriteLine(value.ToString(thTH))

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

文化特性的目前行事曆也會用於該文化特性的所有剖析作業中,如下列範例所示。A culture's current calendar is also used in all parsing operations for that culture, as the following example shows.

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

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

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

您可以使用特定行事曆的日期和時間專案(年、月和日的數位)來具現化 @no__t 0 值,方法是呼叫包含 @no__t 2 參數的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. 下列範例會使用來自 ThaiBuddhistCalendar 行事曆的日期和時間元素。The following example uses the date and time elements from the ThaiBuddhistCalendar calendar.

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

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

@no__t 0 不包含 @no__t 1 參數的函式,會假設日期和時間元素會以西曆中的單位表示。DateTime constructors that do not include a calendar parameter assume that the date and time elements are expressed as units in the Gregorian calendar.

所有其他 @no__t 0 的屬性和方法都會使用西曆。All other DateTime properties and methods use the Gregorian calendar. 例如,DateTime.Year 屬性會傳回西曆中的年份,而 @no__t 1 方法則假設 year 參數是西曆中的年份。For example, the DateTime.Year property returns the year in the Gregorian calendar, and the DateTime.IsLeapYear(Int32) method assumes that the year parameter is a year in the Gregorian calendar. 使用西曆的每個 @no__t 0 成員,都有一個對應的 Calendar 類別的成員,而該類別會使用特定的行事曆。Each DateTime member that uses the Gregorian calendar has a corresponding member of the Calendar class that uses a specific calendar. 例如,Calendar.GetYear 方法會傳回特定行事曆中的年份,而 Calendar.IsLeapYear 方法會將 year 參數解讀為特定行事曆中的年份號碼。For example, the Calendar.GetYear method returns the year in a specific calendar, and the Calendar.IsLeapYear method interprets the year parameter as a year number in a specific calendar. 下列範例會使用 DateTimeThaiBuddhistCalendar 類別的對應成員。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 結構包含 DayOfWeek 屬性,會傳回西曆中的星期幾。The DateTime structure includes a DayOfWeek property that returns the day of the week in the Gregorian calendar. 它不會包含可讓您抓取年度周數的成員。It does not include a member that allows you to retrieve the week number of the year. 若要取出一年中的第幾周,請呼叫個別行事曆的 Calendar.GetWeekOfYear 方法。To retrieve the week of the year, call the individual calendar's Calendar.GetWeekOfYear method. 下列範例提供一個實例。The following example provides an illustration.

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

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

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

如需日期和行事曆的詳細資訊,請參閱使用行事曆For more information on dates and calendars, see Working with Calendars.

保存日期時間值Persisting DateTime values

您可以用四種方式保存 DateTime 值:You can persist DateTime values in four ways:

您必須確定還原 @no__t 0 值的常式不會遺失資料,也不會擲回例外狀況,不論您選擇哪一種技術。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. 使用不因文化特性而異的慣例,呼叫 Parse(String, IFormatProvider, DateTimeStyles) 或 @no__t 1 多載來還原字串。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) 或 @no__t 2 多載,這些多載會使用目前線程文化特性的慣例。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.

DateTime 值保存為字串時最常見的錯誤是依賴預設或目前文化特性的格式化慣例。The most common error made when persisting DateTime values as strings is to rely on the formatting conventions of the default or current culture. 當儲存和還原字串時,如果目前的文化特性不同,就會發生問題。Problems arise if the current culture is different when saving and restoring the strings. 下列範例說明這些問題。The following example illustrates these problems. 它會使用目前文化特性的格式化慣例來儲存五個日期,在此案例中為英文(美國)。It saves five dates using the formatting conventions of the current culture, which in this case is English (United States). 它會使用不同文化特性的格式設定慣例來還原日期,在此案例中為英文(英國)。It restores the dates using the formatting conventions of a different culture, which in this case is English (Great Britain). 因為這兩個文化特性的格式設定慣例不同,所以無法還原其中兩個日期,而其餘的三個日期則會不正確地轉譯。Because the formatting conventions of the two cultures are different, two of the dates can't be restored, and the remaining three dates are interpreted incorrectly. 此外,如果原始的日期和時間值代表單一時間,則還原的時間會不正確,因為遺失時區資訊。Also, if the original date and time values represent single moments in time, the restored times are incorrect because time zone information is lost.

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

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

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

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

Private Sub RestoreDatesAsStrings()
    TimeZoneInfo.ClearCachedData()
    Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}")
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
    Dim sr As New StreamReader(filenameTxt)
    Dim inputValues As String() = sr.ReadToEnd().Split({"|"c}, StringSplitOptions.RemoveEmptyEntries)
    sr.Close()
    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each inputValue In inputValues
        Dim dateValue As Date
        If DateTime.TryParse(inputValue, dateValue) Then
            Console.WriteLine($"'{inputValue}' --> {dateValue:f}")
        Else
            Console.WriteLine($"Cannot parse '{inputValue}'")
        End If
    Next
    Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
'       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
'       The dates on an en-US system:
'       Saturday, June 14, 2014 6:32 AM
'       Thursday, July 10, 2014 11:49 PM
'       Saturday, January 10, 2015 1:16 AM
'       Saturday, December 20, 2014 9:45 PM
'       Monday, June 02, 2014 3:14 PM
'       Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
'       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
'       The dates on an en-GB system:
'       Cannot parse '6/14/2014 6:32:00 AM'
'       '7/10/2014 11:49:00 PM' --> 07 October 2014 23:49
'       '1/10/2015 1:16:00 AM' --> 01 October 2015 01:16
'       Cannot parse '12/20/2014 9:45:00 PM'
'       '6/2/2014 3:14:00 PM' --> 06 February 2014 15:14
'       Restored dates...

若要成功地來回 DateTime 值,請遵循下列步驟:To round-trip DateTime values successfully, follow these steps:

  1. 如果這些值代表一段時間,請呼叫 ToUniversalTime 方法,將它們從當地時間轉換成 UTC。If the values represent single moments of time, convert them from the local time to UTC by calling the ToUniversalTime method.
  2. 藉由呼叫 ToString(String, IFormatProvider) 或 @no__t 1 多載,將日期轉換成其字串表示。Convert the dates to their string representations by calling the ToString(String, IFormatProvider) or String.Format(IFormatProvider, String, Object[]) overload. 使用不因文化特性而異的格式設定慣例,方法是指定 CultureInfo.InvariantCulture 做為 provider 引數。Use the formatting conventions of the invariant culture by specifying CultureInfo.InvariantCulture as the provider argument. 指定此值應使用 "O" 或 "R" 標準格式字串來進行來回行程。Specify that the value should round-trip by using the "O" or "R" standard format string.

若要還原保存的 DateTime 值而不遺失資料,請遵循下列步驟:To restore the persisted DateTime values without data loss, follow these steps:

  1. 藉由呼叫 ParseExact 或 @no__t 1 多載來剖析資料。Parse the data by calling the ParseExact or TryParseExact overload. 指定 CultureInfo.InvariantCulture 做為 provider 引數,並使用您在轉換期間用於 format 引數的相同標準格式字串。Specify CultureInfo.InvariantCulture as the provider argument, and use the same standard format string you used for the format argument during conversion. styles 引數中包含 DateTimeStyles.RoundtripKind 值。Include the DateTimeStyles.RoundtripKind value in the styles argument.
  2. 如果 DateTime 值代表單一時間,請呼叫 ToLocalTime 方法,將剖析的日期從 UTC 轉換為當地時間。If the DateTime values represent single moments in time, call the ToLocalTime method to convert the parsed date from UTC to local time.

下列範例會使用不因文化特性和 "O" 標準格式字串,確保儲存和還原的 @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.

若要將 DateTime 值保存為整數:To persist a DateTime value as an integer:

  • 如果 DateTime 值代表單一時間,請呼叫 ToUniversalTime 方法,將它們轉換成 UTC。If the DateTime values represent single moments in time, convert them to UTC by calling the ToUniversalTime method.
  • 從其 Ticks 屬性中取出 DateTime 值所表示的刻度數目。Retrieve the number of ticks represented by the DateTime value from its Ticks property.

若要還原已保存為整數的 DateTime 值:To restore a DateTime value that has been persisted as an integer:

  1. 藉由將 Int64 值傳遞至 DateTime(Int64) 的函式,具現化新的 @no__t 0 物件。Instantiate a new DateTime object by passing the Int64 value to the DateTime(Int64) constructor.
  2. 如果 DateTime 值代表單一時間點,請呼叫 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

您可以透過序列化,將 DateTime 值保存到資料流程或檔案,然後透過還原序列化來還原它們。You can persist DateTime values through serialization to a stream or file, and then restore them through deserialization. DateTime 資料會以某些指定的物件格式進行序列化。DateTime data is serialized in some specified object format. 當物件還原序列化時,就會還原這些物件。The objects are restored when they are deserialized. 格式器或序列化程式(例如 XmlSerializerBinaryFormatter)會處理序列化和還原序列化的進程。A formatter or serializer, such as XmlSerializer or BinaryFormatter, handles the process of serialization and deserialization. 如需有關序列化以及 .NET Framework 所支援之序列化類型的詳細資訊,請參閱序列化For more information about serialization and the types of serialization supported by the .NET Framework, see Serialization.

下列範例會使用 XmlSerializer 類別來序列化和還原序列化 DateTime 值。The following example uses the XmlSerializer class to serialize and deserialize DateTime values. 這些值代表二十第一個世紀的所有閏日。The values represent all leap year days in the twenty-first century. 如果此範例是在目前文化特性為英文(英國)的系統上執行,則輸出會代表其結果。The output represents the result if the example is run on a system whose current culture is English (Great Britain). 由於您已還原序列化 DateTime 物件本身,因此程式碼不需要處理日期和時間格式的文化差異。Because you've deserialized the DateTime object itself, the code doesn't have to handle cultural differences in date and time formats.

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

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

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

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

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

    ' Display the dates.
    Console.WriteLine($"Leap year days from 2000-2100 on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    Dim nItems As Integer
    For Each dat In deserializedDates
        Console.Write($"   {dat:d}     ")
        nItems += 1
        If nItems Mod 5 = 0 Then Console.WriteLine()
    Next
End Sub
' The example displays the following output:
'    Leap year days from 2000-2100 on an en-GB system:
'       29/02/2000       29/02/2004       29/02/2008       29/02/2012       29/02/2016
'       29/02/2020       29/02/2024       29/02/2028       29/02/2032       29/02/2036
'       29/02/2040       29/02/2044       29/02/2048       29/02/2052       29/02/2056
'       29/02/2060       29/02/2064       29/02/2068       29/02/2072       29/02/2076
'       29/02/2080       29/02/2084       29/02/2088       29/02/2092       29/02/2096

上一個範例不包含時間資訊。The previous example doesn't include time information. 如果 DateTime 值代表時間點,並以本地時程表示,則會先將它從本地時間轉換成 UTC,再藉由呼叫 ToUniversalTime 方法進行序列化。If a DateTime value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the ToUniversalTime method. 在還原序列化之後,藉由呼叫 ToLocalTime 方法,將它從 UTC 轉換為當地時間。After you deserialize it, convert it from UTC to local time by calling the ToLocalTime method. 下列範例會使用 BinaryFormatter 類別,將美國的系統上的 @no__t 1 資料序列化太平洋標準時區,並在美國的系統上將其還原序列化中央標準區域。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 結構不是時區感知,所以您必須序列化 DateTime 值和代表其時區的 @no__t 2 物件。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 0 值和其時區。Create a type whose fields include both the DateTime value and its time zone. 下列範例會定義 DateWithTimeZone 結構。The following example defines a DateWithTimeZone structure.

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

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

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

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

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

重要

在接下來的兩個範例中,會使用 DateWithTimeZone 結構,將 @no__t 1 物件的陣列序列化和還原序列化。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 1 物件的陣列。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

日期時間與TimeSpanDateTime vs. TimeSpan

@No__t-0 和 @no__t 1 數值型別的差異在於,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. 或者,您可以將正數 TimeSpan 加入目前的 DateTime,以取得代表未來日期的 DateTime 值。Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date.

您可以從 DateTime 物件中新增或減去時間間隔。You can add or subtract a time interval from a DateTime object. 時間間隔可以是負數或正數,而且可以用單位(例如刻度、秒或 @no__t 0 物件)來表示。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-0 值的相等比較是精確的。Equality comparisons for DateTime values are exact. 這表示兩個值必須表示為相同的刻度數,才能視為相等。That means two values must be expressed as the same number of ticks to be considered equal. 對於許多應用程式來說,該精確度通常不需要或甚至不正確。That precision is often unnecessary or even incorrect for many applications. 通常,您會想要測試 DateTime 物件是否大致相等Often, you want to test if DateTime objects are roughly equal.

下列範例示範如何比較大致相等的 DateTime 值。The following example demonstrates how to compare roughly equivalent DateTime values. 當宣告相等時,它會接受差異較小的邊界。It accepts a small margin of difference when declaring them equal.

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

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

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

    Return Math.Abs(delta) < windowInSeconds
End Function

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

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

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

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

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

COM Interop 考慮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 的行為表示,如果您的應用程式反復存取僅指定時間的 DateTime,則您的應用程式必須記得修改或忽略最後 DateTime 物件中的錯誤日期。The behavior of the .NET Framework and COM means that if your application round-trips a DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final DateTime object.

建構函式

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

DateTime 結構的新執行個體初始化為刻度的指定數目。Initializes a new instance of the DateTime structure to a specified number of ticks.

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

DateTime 結構的新執行個體初始化為指定的刻度數以及國際標準時間 (UTC) 或本地時間。Initializes a new instance of the DateTime structure to a specified number of ticks and to Coordinated Universal Time (UTC) or local time.

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

DateTime 結構的新執行個體初始化為指定的年、月和日。Initializes a new instance of the DateTime structure to the specified year, month, and day.

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月和日。Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar.

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

DateTime 結構的新執行個體初始化為指定的年、月、日、時、分和秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second.

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

DateTime 結構的新執行個體初始化為指定年、月、日、時、分、秒以及國際標準時間 (UTC) 或本地時間。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and Coordinated Universal Time (UTC) or local time.

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分和秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second for the specified calendar.

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

DateTime 結構的新執行個體初始化為指定的年、月、日、時、分、秒和毫秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond.

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

DateTime 結構的新執行個體初始化為指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time.

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒和毫秒。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified calendar.

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.

欄位

MaxValue MaxValue MaxValue MaxValue

代表 DateTime 最大的可能值。Represents the largest possible value of DateTime. 此欄位為唯讀。This field is read-only.

MinValue MinValue MinValue MinValue

代表 DateTime 最小的可能值。Represents the smallest possible value of DateTime. 此欄位為唯讀。This field is read-only.

UnixEpoch UnixEpoch UnixEpoch UnixEpoch

屬性

Date Date Date Date

取得這個執行個體的日期部分。Gets the date component of this instance.

Day Day Day Day

取得由這個執行個體表示的月份天數。Gets the day of the month represented by this instance.

DayOfWeek DayOfWeek DayOfWeek DayOfWeek

取得由這個執行個體表示的一週天數。Gets the day of the week represented by this instance.

DayOfYear DayOfYear DayOfYear DayOfYear

取得由這個執行個體表示的一年天數。Gets the day of the year represented by this instance.

Hour Hour Hour Hour

取得這個執行個體所表示日期的小時元件。Gets the hour component of the date represented by this instance.

Kind Kind Kind Kind

取得值,指出這個執行個體表示的時間是根據本地時間、國際標準時間 (UTC),或兩者皆非。Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.

Millisecond Millisecond Millisecond Millisecond

取得這個執行個體所表示日期的毫秒元件。Gets the milliseconds component of the date represented by this instance.

Minute Minute Minute Minute

取得這個執行個體所表示日期的分鐘元件。Gets the minute component of the date represented by this instance.

Month Month Month Month

取得這個執行個體所表示日期的月份元件。Gets the month component of the date represented by this instance.

Now Now Now Now

取得 DateTime 物件,此物件會設定為這部電腦上目前的日期和時間,以本地時間表示。Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

Second Second Second Second

取得這個執行個體所表示日期的秒數元件。Gets the seconds component of the date represented by this instance.

Ticks Ticks Ticks Ticks

取得表示這個執行個體日期和時間的刻度數目。Gets the number of ticks that represent the date and time of this instance.

TimeOfDay TimeOfDay TimeOfDay TimeOfDay

取得這個執行個體的一天時間。Gets the time of day for this instance.

Today Today Today Today

取得目前的日期。Gets the current date.

UtcNow UtcNow UtcNow UtcNow

取得 DateTime 物件,此物件會設定為這部電腦上目前的日期和時間,以國際標準時間 (UTC) 表示。Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

Year Year Year Year

取得這個執行個體所表示日期的年份元件。Gets the year component of the date represented by this instance.

方法

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

傳回新的 DateTime,將這個執行個體的值加上指定之 TimeSpan 的值。Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的天數。Returns a new DateTime that adds the specified number of days to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的時數。Returns a new DateTime that adds the specified number of hours to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的毫秒數。Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的分鐘數。Returns a new DateTime that adds the specified number of minutes to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的月數。Returns a new DateTime that adds the specified number of months to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的秒數。Returns a new DateTime that adds the specified number of seconds to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的刻度數。Returns a new DateTime that adds the specified number of ticks to the value of this instance.

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

傳回新的 DateTime,將這個執行個體的值加上指定的年數。Returns a new DateTime that adds the specified number of years to the value of this instance.

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

比較 DateTime 的兩個執行個體,並傳回整數,這個整數表示第一個執行個體早於、同於或晚於第二個執行個體。Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

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

比較這個執行個體的值與指定的 DateTime 值,並且傳回一個整數,指出這個執行個體是早於、同於或晚於指定的 DateTime 值。Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

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

比較這個執行個體的值與含有指定之 DateTime 值的指定物件,並且傳回一個整數,指出這個執行個體是早於、同於或晚於指定的 DateTime 值。Compares the value of this instance to a specified object that contains a specified DateTime value, and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

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

傳回所指定年份中指定月份的天數。Returns the number of days in the specified month and year.

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

傳回值,指出兩個 DateTime 執行個體是否有相同的日期和時間值。Returns a value indicating whether two DateTime instances have the same date and time value.

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

傳回值,該值指出這個執行個體的值是否等於指定之 DateTime 執行個體的值。Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance.

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

傳回值,指出這個執行個體 (Instance) 是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object.

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

還原序列化 64 位元的二進位值,並重新建立原始的序列化 DateTime 物件。Deserializes a 64-bit binary value and recreates an original serialized DateTime object.

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

將指定的 Windows 檔案時間轉換成相等的本地時間。Converts the specified Windows file time to an equivalent local time.

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

將指定的 Windows 檔案時間轉換成相等的 UTC 時間。Converts the specified Windows file time to an equivalent UTC time.

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

傳回等於指定 OLE Automation 日期的 DateTimeReturns a DateTime equivalent to the specified OLE Automation Date.

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

將這個執行個體的值轉換為標準日期和時間格式規範所支援的所有字串表示。Converts the value of this instance to all the string representations supported by the standard date and time format specifiers.

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

將這個執行個體的值轉換為指定的標準日期和時間格式規範所支援的所有字串表示。Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier.

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

將這個執行個體的值轉換為標準日期和時間格式規範和指定的特定文化特性格式資訊所支援的所有字串表示。Converts the value of this instance to all the string representations supported by the standard date and time format specifiers and the specified culture-specific formatting information.

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

將這個執行個體的值轉換為指定的標準日期和時間格式規範和特定文化特性格式資訊所支援的所有字串表示。Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier and culture-specific formatting information.

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

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

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

傳回實值類型 TypeCodeDateTimeReturns the TypeCode for value type DateTime.

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

指出這個 DateTime 執行個體是否在目前時區的日光節約時間範圍內。Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone.

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

傳回指定年份是否為閏年的指示。Returns an indication whether the specified year is a leap year.

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

使用目前執行緒文化特性的慣例,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using the conventions of the current thread culture.

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

使用特定文化特性格式資訊,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

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

使用文化特定格式資訊及格式化樣式,將包含日期與時間字串表示的記憶體範圍轉換成相等 DateTimeConverts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

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

使用特定文化特性格式資訊及格式樣式,將日期和時間的字串表示轉換為其相等的 DateTimeConverts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

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

使用指定的格式以及特定文化特性的格式資訊,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly.

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

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。The format of the string representation must match the specified format exactly or an exception is thrown.

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定的格式,否則會擲回例外狀況。The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

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

建立新的 DateTime 物件,此物件的刻度數與指定的 DateTime 相同,但依指定的 DateTimeKind 值所示,指定為本地時間、國際標準時間 (Coordinated Universal Time,UTC),或兩者都不是。Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.

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

傳回會將指定日期和時間從此執行個體的值減去的新 DateTimeReturns a new DateTime that subtracts the specified date and time from the value of this instance.

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

傳回會將指定期間從此執行個體的值減去的新 DateTimeReturns a new DateTime that subtracts the specified duration from the value of this instance.

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

將目前的 DateTime 物件序列化成 64 位元的二進位值,之後可以用這個值來重新建立 DateTime 物件。Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object.

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

將目前 DateTime 物件的值轉換成 Windows 檔案時間。Converts the value of the current DateTime object to a Windows file time.

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

將目前 DateTime 物件的值轉換成 Windows 檔案時間。Converts the value of the current DateTime object to a Windows file time.

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

將目前 DateTime 物件的值轉換成本地時間。Converts the value of the current DateTime object to local time.

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

將目前 DateTime 物件的值轉換為其相等的完整日期 (Long Date) 字串表示。Converts the value of the current DateTime object to its equivalent long date string representation.

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

將目前 DateTime 物件的值轉換為其相等的完整時間 (Long Time) 字串表示。Converts the value of the current DateTime object to its equivalent long time string representation.

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

將這個執行個體的值轉換為相等的 OLE Automation 日期。Converts the value of this instance to the equivalent OLE Automation date.

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

將目前 DateTime 物件的值轉換為其相等的簡短日期 (Short Date) 字串表示。Converts the value of the current DateTime object to its equivalent short date string representation.

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

將目前 DateTime 物件的值轉換為其相等的簡短時間 (Short Time) 字串表示。Converts the value of the current DateTime object to its equivalent short time string representation.

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

使用指定的格式和特定文化特性的格式資訊,將目前 DateTime 物件的值,轉換為其相等的字串表示。Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.

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

使用指定的格式和目前文化特性的格式化慣例,將目前 DateTime 物件的值轉換為其相等的字串表示。Converts the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture.

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

使用指定的特定文化特性格式資訊,將目前 DateTime 物件的值轉換為其相等的字串表示。Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information.

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

使用目前文化特性的格式化慣例,將目前 DateTime 物件的值轉換為其相等的字串表示。Converts the value of the current DateTime object to its equivalent string representation using the formatting conventions of the current culture.

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

將目前 DateTime 物件的值轉換成國際標準時間 (UTC)。Converts the value of the current DateTime object to Coordinated Universal Time (UTC).

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

將日期和時間的指定字串表示,轉換為其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

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

使用指定的特定文化特性格式資訊和格式樣式,將日期和時間的指定字串表示轉換為其相等的 DateTime,並傳回值,這個值表示轉換是否成功。Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

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

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. 字串表示的格式必須完全符合指定的格式。The format of the string representation must match the specified format exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTimeConverts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. 字串表示的格式必須至少完全符合其中一個指定格式。The format of the string representation must match at least one of the specified formats exactly. 此方法會傳回值,這個值表示轉換是否成功。The method returns a value that indicates whether the conversion succeeded.

運算子

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

將指定的日期和時間加上指定的時間間隔,產生新的日期和時間。Adds a specified time interval to a specified date and time, yielding a new date and time.

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

判斷 DateTime 的兩個指定執行個體是否相等。Determines whether two specified instances of DateTime are equal.

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

判斷某個指定的 DateTime 是否晚於另一個指定的 DateTimeDetermines whether one specified DateTime is later than another specified DateTime.

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

判斷某個指定之 DateTime 表示的是同於還是晚於另一個指定之 DateTime 的日期和時間。Determines whether one specified DateTime represents a date and time that is the same as or later than another specified DateTime.

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

判斷 DateTime 的兩個指定執行個體是否不相等。Determines whether two specified instances of DateTime are not equal.

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

判斷某個指定的 DateTime 是否早於另一個指定的 DateTimeDetermines whether one specified DateTime is earlier than another specified DateTime.

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

判斷某個指定之 DateTime 表示的是同於還是早於另一個指定之 DateTime 的日期和時間。Determines whether one specified DateTime represents a date and time that is the same as or earlier than another specified DateTime.

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

將指定的日期和時間減去指定的時間間隔,並傳回新的日期和時間。Subtracts a specified time interval from a specified date and time and returns a new date and time.

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

將另一個指定的日期和時間減去指定的日期和時間,並傳回時間間隔。Subtracts a specified date and time from another specified date and time and returns a time interval.

明確介面實作

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

傳回目前的 DateTime物件。Returns the current DateTime object.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

將目前的 DateTime 物件轉換為指定類型的物件。Converts the current DateTime object to an object of a specified type.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

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

使用序列化目前 SerializationInfo 物件所需的資料,填入 DateTime 物件。Populates a SerializationInfo object with the data needed to serialize the current DateTime object.

適用於

執行緒安全性

此類型的所有成員都是安全線程。All members of this type are thread safe. 出現在修改實例狀態的成員實際上會傳回以新值初始化的新實例。Members that appear to modify instance state actually return a new instance initialized with the new value. 如同任何其他類型,讀取和寫入包含此類型之實例的共用變數必須受到鎖定保護,以確保執行緒安全性。As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

另請參閱