DateTime 結構

定義

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

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

備註

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 此變更對使用這些日曆的所有應用程式都有影響。Such a change of era affects all applications that use these calendars. 若要取得詳細資訊及判斷您的應用程式是否受影響,請參閱 Handling a new era in the Japanese calendar in .NET (處理 .NET 中日本日曆的新紀元)。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 若要了解如何在 Windows 系統上測試您的應用程式,確保其已準備好面對紀元變更,請參閱 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.

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

初始化範例Initialization Examples

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

將字串剖析為 DateTime 物件Parsing strings as DateTime objects

DateTime 解析度DateTime resolution

文化特性和行事曆Culture and calendars

持續性Persistence

本章節包含結構的許多常見用法的主題 DateTimeThis section contains topics for many common uses of the DateTime struct:

DateTime數值型別代表日期和時間,其值範圍從 00:00:00 (午夜) 、 (0001 年1月1日、0001年1月1日) 到11:59:59 年12月31日,西元9999The 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 年1月1日午夜的滴答數A particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (日曆中的西元 ) GregorianCalendar(C.E.) in the GregorianCalendar calendar. 此數目不包括由閏秒新增的刻度。The number excludes ticks that would be added by leap seconds. 例如,31241376000000000L 的刻度值代表0100年1月1日星期五,午夜為12:00:00。For example, a ticks value of 31241376000000000L represents the date Friday, January 01, 0100 12:00:00 midnight. DateTime值一律會以明確或預設行事曆的內容表示。A DateTime value is always expressed in the context of an explicit or default calendar.

注意

如果您要使用您想要轉換成某個其他時間間隔的刻度值(例如分鐘或秒),則應該使用 TimeSpan.TicksPerDay 、、 TimeSpan.TicksPerHour TimeSpan.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. 例如,若要將指定的刻度數目所表示的秒數加入至值的 Second 元件 DateTime ,您可以使用運算式 dateValue.Second + nTicks/Timespan.TicksPerSecondFor example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

您可以從 GitHub 上的檔存放庫中的 Visual Basicc # ,查看本文中整組範例的來源。You can view the source for the entire set of examples from this article in either Visual Basic or C# from the docs repository on GitHub.

注意

DateTime使用特定時區的日期和時間值之結構的替代方案是 DateTimeOffset 結構。An alternative to the DateTime structure for working with date and time values in particular time zones is the DateTimeOffset structure. DateTimeOffset 結構會將日期和時間資訊儲存在私用 DateTime 欄位中,以及該日期和時間與私用欄位中 UTC 不同的分鐘數 Int16The DateTimeOffset structure stores date and time information in a private DateTime field and the number of minutes by which that date and time differs from UTC in a private Int16 field. 這可讓 DateTimeOffset 值反映特定時區的時間,而 DateTime 值可以明確地反映 UTC 和本地時區的時間。This makes it possible for a DateTimeOffset value to reflect the time in a particular time zone, whereas a DateTime value can unambiguously reflect only UTC and the local time zone's time. 如需 DateTime DateTimeOffset 處理日期和時間值時使用結構或結構的相關討論,請參閱在 DateTime、DateTimeOffset、TimeSpan 和 TimeZoneInfo 之間選擇For a discussion about when to use the DateTime structure or the DateTimeOffset structure when working with date and time values, see Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo.

初始化 DateTime 物件Initializing a DateTime object

您可以使用許多不同的方式,將初始值指派給新的 DateTime 值:You can assign an initial value to a new DateTime value in many different ways:

  • 呼叫函式,您可以在其中指定值的引數,或使用隱含無參數的函式。Calling a constructor, either one where you specify arguments for values, or use the implicit parameterless constructor.
  • 將指派 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 函數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 指定 year、month、day、hour、minute 和 second 的函式來建立特定日期。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. (如需實值型別之隱含無參數函式的詳細資訊,請參閱實 數值型別。 ) 某些編譯器也支援宣告 DateTime 值,而不需要明確指派值給它。(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. 下列範例說明 DateTime c # 和 Visual Basic 中的隱含無參數函式,以及 DateTime 未在 Visual Basic 中指派的宣告。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.

Dim dat1 As 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(Date.MinValue))

Dim dat2 As New DateTime()
' The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat2.ToString(System.Globalization.CultureInfo.InvariantCulture))
' The following method call displays True.
Console.WriteLine(dat2.Equals(Date.MinValue))
var dat1 = new DateTime();
// The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
// The following method call displays True.
Console.WriteLine(dat1.Equals(DateTime.MinValue));
指派計算值Assigning a computed value

您可以指派 DateTime 屬性或方法所傳回的日期和時間值給物件。You can assign the DateTime object a date and time value returned by a property or method. 下列範例會將目前的日期和時間、目前的國際標準時間 (UTC) 日期和時間,以及目前的日期指派給三個新的 DateTime 變數。The following example assigns the current date and time, the current Coordinated Universal Time (UTC) date and time, and the current date to three new DateTime variables.

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

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.UtcNow;
DateTime date3 = DateTime.Today;
剖析代表日期時間的字串Parsing a string that represents a DateTime

ParseParseExactTryParseTryParseExact 方法都會將字串轉換為其相等的日期和時間值。The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. 下列範例 Parse 會使用和 ParseExact 方法來剖析字串,並將它轉換成 DateTime 值。The following examples use the Parse and ParseExact methods to parse a string and convert it to a DateTime value. 第二種格式是使用 ISO 8601 標準所支援的表單,表示字串格式的日期和時間。The second format uses a form supported by the ISO 8601 standard for a representing date and time in string format. 此標準表示通常用來在 web 服務中傳輸日期資訊。This standard representation is often used to transfer date information in web services.

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

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

TryParseTryParseExact 方法會指出字串是否為有效的值表示, DateTime 如果是,則會執行轉換。The TryParse and TryParseExact methods indicate whether a string is a valid representation of a DateTime value and, if it is, performs the conversion.

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

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

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

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

就內部而言,所有 DateTime 值都是以刻度的數目表示, (自0001年1月1日午夜起自12:00:00 年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. 值的外觀 DateTime 是格式化作業的結果,會將值轉換成其字串表示。The appearance of a DateTime value is the result of a formatting operation that converts a value to its string representation.

日期和時間值的外觀取決於文化特性、國際標準、應用程式需求和個人喜好設定。The appearance of date and time values is dependent on culture, international standards, application requirements, and personal preference. DateTime結構提供透過的多載來格式化日期和時間值的彈性 ToStringThe DateTime structure offers flexibility in formatting date and time values through overloads of ToString. 預設 DateTime.ToString() 方法會使用目前文化特性的簡短日期和完整時間模式,傳回日期和時間值的字串表示。The default DateTime.ToString() method returns the string representation of a date and time value using the current culture's short date and long time pattern. 下列範例會使用預設 DateTime.ToString() 方法。The following example uses the default DateTime.ToString() method. 它會使用目前文化特性的簡短日期和完整時間模式來顯示日期和時間。It displays the date and time using the short date and long time pattern for the current culture. En-us 文化特性是執行範例之電腦上的目前文化特性。The en-US culture is the current culture on the computer on which the example was run.

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

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

您可能需要將特定文化特性的日期格式化,以支援伺服器可能與用戶端不同文化特性的 web 案例。You may need to format dates in a specific culture to support web scenarios where the server may be in a different culture from the client. 您可以使用方法來指定文化特性, DateTime.ToString(IFormatProvider) 以建立特定文化特性的簡短日期和完整時程表示法。You specify the culture using the DateTime.ToString(IFormatProvider) method to create the short date and long time representation in a specific culture. 下列範例會使用 DateTime.ToString(IFormatProvider) 方法,以 fr 文化特性的簡短日期和完整時間模式來顯示日期和時間。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.

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

其他應用程式可能需要日期的不同字串表示。Other applications may require different string representations of a date. DateTime.ToString(String)方法會使用目前文化特性的格式化慣例,傳回標準或自訂格式規範所定義的字串表示。The DateTime.ToString(String) method returns the string representation defined by a standard or custom format specifier using the formatting conventions of the current culture. 下列範例會使用 DateTime.ToString(String) 方法來顯示 en-us 文化特性的完整日期和時間模式,也就是執行範例之電腦上的目前文化特性。The following example uses the DateTime.ToString(String) method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run.

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

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

最後,您可以使用方法來指定文化特性和格式 DateTime.ToString(String, IFormatProvider)Finally, you can specify both the culture and the format using the DateTime.ToString(String, IFormatProvider) method. 下列範例會使用 DateTime.ToString(String, IFormatProvider) 方法來顯示 fr-fr 文化特性的完整日期和時間模式。The following example uses the DateTime.ToString(String, IFormatProvider) method to display the full date and time pattern for the fr-FR culture.

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

多載 DateTime.ToString(String) 也可以搭配使用自訂格式字串來指定其他格式。The DateTime.ToString(String) overload can also be used with a custom format string to specify other formats. 下列範例顯示如何使用通常用於 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.

var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("yyyyMMddTHH:mm:ssZ"));
// Displays 20080301T07:00:00Z
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.

從字串剖析 DateTime 值Parsing DateTime values from strings

剖析會將日期和時間的字串表示轉換成 DateTime 值。Parsing converts the string representation of a date and time to a DateTime value. 一般而言,日期和時間字串在應用程式中有兩種不同的使用方式:Typically, date and time strings have two different usages in applications:

  • 日期和時間會採用各式各樣的表單,並反映目前文化特性或特定文化特性的慣例。A date and time takes a variety of forms and reflects the conventions of either the current culture or a specific culture. 例如,應用程式可讓目前文化特性為 en-us 的使用者輸入日期值為 "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-us 的使用者輸入日期值為 "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 方法,將字串從文化特性所使用的其中一個一般日期和時間格式轉換成 DateTime 值。You use the Parse or TryParse method to convert a string from one of the common date and time formats used by a culture to a DateTime value. 下列範例顯示如何使用將 TryParse 不同文化特性格式的日期字串轉換成 DateTime 值。The following example shows how you can use TryParse to convert date strings in different culture-specific formats to a DateTime value. 它會將目前文化特性變更為英文 (英國) ,然後呼叫 GetDateTimeFormats() 方法來產生日期和時間字串的陣列。It changes the current culture to English (Great Britain) and calls the GetDateTimeFormats() method to generate an array of date and time strings. 然後,它會將陣列中的每個元素傳遞給 TryParse 方法。It then passes each element in the array to the TryParse method. 範例的輸出顯示剖析方法能夠成功地轉換每個特定文化特性的日期和時間字串。The output from the example shows the parsing method was able to successfully convert each of the culture-specific date and time strings.

System.Threading.Thread.CurrentThread.CurrentCulture =
    System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");

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

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

// Display strings that could not be parsed.
if (badFormats.Count > 0)
{
    Console.WriteLine("\nStrings that could not be parsed: ");
    foreach (var badFormat in badFormats)
        Console.WriteLine($"   {badFormat}");
}
// Press "Run" to see the output.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")

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

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

' Display strings that could not be parsed.
If badFormats.Count > 0 Then
    Console.WriteLine()
    Console.WriteLine("Strings that could not be parsed: ")
    For Each badFormat In badFormats
        Console.WriteLine($"   {badFormat}")
    Next
End If
' The example displays the following output:
'       Date String                           Date               
'       
'       01/06/2013                            01/06/2013 00:00:00
'       01/06/13                              01/06/2013 00:00:00
'       1/6/13                                01/06/2013 00:00:00
'       1.6.13                                01/06/2013 00:00:00
'       2013-06-01                            01/06/2013 00:00:00
'       01 June 2013                          01/06/2013 00:00:00
'       1 June 2013                           01/06/2013 00:00:00
'       01 June 2013 12:32                    01/06/2013 12:32:00
'       01 June 2013 12:32                    01/06/2013 12:32:00
'       01 June 2013 12:32 PM                 01/06/2013 12:32:00
'       01 June 2013 12:32 PM                 01/06/2013 12:32:00
'       1 June 2013 12:32                     01/06/2013 12:32:00
'       1 June 2013 12:32                     01/06/2013 12:32:00
'       1 June 2013 12:32 PM                  01/06/2013 12:32:00
'       1 June 2013 12:32 PM                  01/06/2013 12:32:00
'       01 June 2013 12:32:30                 01/06/2013 12:32:30
'       01 June 2013 12:32:30                 01/06/2013 12:32:30
'       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
'       01 June 2013 12:32:30 PM              01/06/2013 12:32:30
'       1 June 2013 12:32:30                  01/06/2013 12:32:30
'       1 June 2013 12:32:30                  01/06/2013 12:32:30
'       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
'       1 June 2013 12:32:30 PM               01/06/2013 12:32:30
'       01/06/2013 12:32                      01/06/2013 12:32:00
'       01/06/2013 12:32                      01/06/2013 12:32:00
'       01/06/2013 12:32 PM                   01/06/2013 12:32:00
'       01/06/2013 12:32 PM                   01/06/2013 12:32:00
'       01/06/13 12:32                        01/06/2013 12:32:00
'       01/06/13 12:32                        01/06/2013 12:32:00
'       01/06/13 12:32 PM                     01/06/2013 12:32:00
'       01/06/13 12:32 PM                     01/06/2013 12:32:00
'       1/6/13 12:32                          01/06/2013 12:32:00
'       1/6/13 12:32                          01/06/2013 12:32:00
'       1/6/13 12:32 PM                       01/06/2013 12:32:00
'       1/6/13 12:32 PM                       01/06/2013 12:32:00
'       1.6.13 12:32                          01/06/2013 12:32:00
'       1.6.13 12:32                          01/06/2013 12:32:00
'       1.6.13 12:32 PM                       01/06/2013 12:32:00
'       1.6.13 12:32 PM                       01/06/2013 12:32:00
'       2013-06-01 12:32                      01/06/2013 12:32:00
'       2013-06-01 12:32                      01/06/2013 12:32:00
'       2013-06-01 12:32 PM                   01/06/2013 12:32:00
'       2013-06-01 12:32 PM                   01/06/2013 12:32:00
'       01/06/2013 12:32:30                   01/06/2013 12:32:30
'       01/06/2013 12:32:30                   01/06/2013 12:32:30
'       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
'       01/06/2013 12:32:30 PM                01/06/2013 12:32:30
'       01/06/13 12:32:30                     01/06/2013 12:32:30
'       01/06/13 12:32:30                     01/06/2013 12:32:30
'       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
'       01/06/13 12:32:30 PM                  01/06/2013 12:32:30
'       1/6/13 12:32:30                       01/06/2013 12:32:30
'       1/6/13 12:32:30                       01/06/2013 12:32:30
'       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
'       1/6/13 12:32:30 PM                    01/06/2013 12:32:30
'       1.6.13 12:32:30                       01/06/2013 12:32:30
'       1.6.13 12:32:30                       01/06/2013 12:32:30
'       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
'       1.6.13 12:32:30 PM                    01/06/2013 12:32:30
'       2013-06-01 12:32:30                   01/06/2013 12:32:30
'       2013-06-01 12:32:30                   01/06/2013 12:32:30
'       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
'       2013-06-01 12:32:30 PM                01/06/2013 12:32:30
'       01 June                               01/06/2013 00:00:00
'       01 June                               01/06/2013 00:00:00
'       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
'       2013-06-01T12:32:30.0000000           01/06/2013 12:32:30
'       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
'       Sat, 01 Jun 2013 12:32:30 GMT         01/06/2013 05:32:30
'       2013-06-01T12:32:30                   01/06/2013 12:32:30
'       12:32                                 22/04/2013 12:32:00
'       12:32                                 22/04/2013 12:32:00
'       12:32 PM                              22/04/2013 12:32:00
'       12:32 PM                              22/04/2013 12:32:00
'       12:32:30                              22/04/2013 12:32:30
'       12:32:30                              22/04/2013 12:32:30
'       12:32:30 PM                           22/04/2013 12:32:30
'       12:32:30 PM                           22/04/2013 12:32:30
'       2013-06-01 12:32:30Z                  01/06/2013 05:32:30
'       01 June 2013 19:32:30                 01/06/2013 19:32:30
'       01 June 2013 19:32:30                 01/06/2013 19:32:30
'       01 June 2013 07:32:30 PM              01/06/2013 19:32:30
'       01 June 2013 7:32:30 PM               01/06/2013 19:32:30
'       1 June 2013 19:32:30                  01/06/2013 19:32:30
'       1 June 2013 19:32:30                  01/06/2013 19:32:30
'       1 June 2013 07:32:30 PM               01/06/2013 19:32:30
'       1 June 2013 7:32:30 PM                01/06/2013 19:32:30
'       June 2013                             01/06/2013 00:00:00
'       June 2013                             01/06/2013 00:00:00

您可以使用 ParseExactTryParseExact 方法,將必須符合特定格式或格式的字串轉換成 DateTime 值。You use the ParseExact and TryParseExact methods to convert a string that must match a particular format or formats to a DateTime value. 您可以指定一或多個日期和時間格式字串做為剖析方法的參數。You specify one or more date and time format strings as a parameter to the parsing method. 下列範例 TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) 會使用方法,將必須是 "yyyyMMdd" 格式或 "HHmmss" 格式的字串轉換成 DateTime 值。The following example uses the TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to DateTime values.

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

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

For Each dateString As String In dateStrings
    If DateTime.TryParseExact(dateString, formats, Nothing,
                           DateTimeStyles.AllowWhiteSpaces Or
                           DateTimeStyles.AdjustToUniversal,
                           parsedDate) Then
        Console.WriteLine($"{dateString} --> {parsedDate:g}")
    Else
        Console.WriteLine($"Cannot convert {dateString}")
    End If
Next
' The example displays the following output:
'       20130816 --> 8/16/2013 12:00 AM
'       Cannot convert 20131608
'         20130816    --> 8/16/2013 12:00 AM
'       115216 --> 4/22/2013 11:52 AM
'       Cannot convert 521116
'         115216   --> 4/22/2013 11:52 AM

的其中一種常見用法 ParseExact 是從 web 服務轉換字串表示,通常是使用 ISO 8601 標準格式。One common use for ParseExact is to convert a string representation from a web service, usually in ISO 8601 standard format. 下列程式碼顯示要使用的正確格式字串:The following code shows the correct format string to use:

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

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

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

日期時間值DateTime values

類型中時間值的描述 DateTime 通常是使用國際標準時間 (UTC) 標準來表示。Descriptions of time values in the DateTime type are often expressed using the Coordinated Universal Time (UTC) standard. 國際標準時間是格林威治標準時間 (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.

如果 Kind 物件的屬性 DateTime 為,則 DateTimeKind.Unspecified 不會指定所表示的時間是否為當地時間、UTC 時間或某個其他時區的時間。If the Kind property of a DateTime object is DateTimeKind.Unspecified, it is unspecified whether the time represented is local time, UTC time, or a time in some other time zone.

日期時間解析DateTime resolution

注意

除了在值上執行日期和時間運算 DateTime 以測量經過的時間之外,您還可以使用 Stopwatch 類別。As an alternative to performing date and time arithmetic on DateTime values to measure elapsed time, you can use the Stopwatch class.

Ticks屬性會以 1 10-百萬分之一秒的單位來表示日期和時間值。The Ticks property expresses date and time values in units of one ten-millionth of a second. 屬性會傳回 Millisecond 日期和時間值中的萬分之一秒。The Millisecond property returns the thousandths of a second in a date and time value. 使用對屬性的重複呼叫 DateTime.Now 來測量經過的時間,取決於系統時鐘。Using repeated calls to the DateTime.Now property to measure elapsed time is dependent on the system clock. Windows 7 和 Windows 8 系統上的系統時鐘的解析度大約為15毫秒。The system clock on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds. 這種解決方式會影響小於100毫秒的短時間間隔。This resolution affects small time intervals less than 100 milliseconds.

下列範例說明在系統時鐘的解析度上,目前日期和時間值的相依性。The following example illustrates the dependence of current date and time values on the resolution of the system clock. 在此範例中,外部迴圈會重複20次,內部迴圈則會延遲外部迴圈。In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. 如果外部迴圈計數器的值為10,則呼叫方法會導致 Thread.Sleep 五毫秒的延遲。If the value of the outer loop counter is 10, a call to the Thread.Sleep method introduces a five-millisecond delay. 下列範例會顯示 DateTime.Now.Milliseconds 只有在呼叫之後,屬性變更所傳回的毫秒數 Thread.SleepThe following example shows the number of milliseconds returned by the DateTime.Now.Milliseconds property changes only after the call to Thread.Sleep.

string output = "";
for (int ctr = 0; ctr <= 20; ctr++)
{
    output += String.Format($"{DateTime.Now.Millisecond}\n");
    // Introduce a delay loop.
    for (int delay = 0; delay <= 1000; delay++)
    { }

    if (ctr == 10)
    {
        output += "Thread.Sleep called...\n";
        System.Threading.Thread.Sleep(5);
    }
}
Console.WriteLine(output);
// Press "Run" to see the output.
Dim output As String = ""
For ctr As Integer = 0 To 20
    output += Date.Now.Millisecond.ToString() + vbCrLf
    ' Introduce a delay loop.
    For delay As Integer = 0 To 1000
    Next

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

DateTime 作業DateTime operations

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

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

DateTime結構本身提供從某個時區轉換為另一個時區的有限支援。The DateTime structure itself offers limited support for converting from one time zone to another. 您可以使用 ToLocalTime 方法將 UTC 轉換為當地時間,或使用 ToUniversalTime 方法從當地時間轉換成 UTC。You can use the ToLocalTime method to convert UTC to local time, or you can use the ToUniversalTime method to convert from local time to UTC. 不過,類別中有一組完整的時區轉換方法可供使用 TimeZoneInfoHowever, a full set of time zone conversion methods is available in the TimeZoneInfo class. 您可以使用這些方法,將世界上任何一個時區的時間轉換為任何其他時區的時間。You convert the time in any one of the world's time zones to the time in any other time zone using these methods.

DateTime只有當物件代表相同時區的時間時,物件的計算和比較才有意義。Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the same time zone. 您可以使用 TimeZoneInfo 物件來代表 DateTime 值的時區,雖然兩者是鬆散結合的。You can use a TimeZoneInfo object to represent a DateTime value's time zone, although the two are loosely coupled. 物件沒有會傳回 DateTime 物件的屬性,該物件表示日期和時間值的時區。A DateTime object does not have a property that returns an object that represents that date and time value's time zone. Kind屬性 DateTime 會指出代表 UTC、本地時間或未指定。The Kind property indicates if a DateTime represents UTC, local time, or is unspecified. 在時區感知應用程式中,您必須依賴一些外部機制來判斷建立物件的時區 DateTimeIn a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a DateTime object was created. 您可以使用包裝值的結構, DateTime 以及 TimeZoneInfo 表示 DateTime 值時區的物件。You could use a structure that wraps both the DateTime value and the TimeZoneInfo object that represents the DateTime value's time zone. 如需在計算中使用 UTC 和值比較的詳細資訊 DateTime ,請參閱使用 日期和時間執行算數運算For details on using UTC in calculations and comparisons with DateTime values, see Performing Arithmetic Operations with Dates and Times.

每個 DateTime 成員都會隱含地使用西曆來執行其作業。Each DateTime member implicitly uses the Gregorian calendar to perform its operation. 例外狀況是隱含指定行事曆的方法。Exceptions are methods that implicitly specify a calendar. 這些包含指定行事曆的函式,以及具有衍生自之參數的方法 IFormatProvider ,例如 System.Globalization.DateTimeFormatInfoThese include constructors that specify a calendar, and methods with a parameter derived from IFormatProvider, such as System.Globalization.DateTimeFormatInfo.

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

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

.NET Framework 類別庫包含數個行事曆類別,所有這些類別都是衍生自 Calendar 類別。The .NET Framework Class Library includes a number of calendar classes, all of which are derived from the Calendar class. 包括:They are:

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. 此變更對使用這些日曆的所有應用程式都有影響。Such a change of era affects all applications that use these calendars. 若要取得詳細資訊及判斷您的應用程式是否受影響,請參閱 Handling a new era in the Japanese calendar in .NET (處理 .NET 中日本日曆的新紀元)。See Handling a new era in the Japanese calendar in .NET for more information and to determine whether your applications are affected. 若要了解如何在 Windows 系統上測試您的應用程式,確保其已準備好面對紀元變更,請參閱 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.CalendarEach culture uses a default calendar defined by its read-only CultureInfo.Calendar property. 每個文化特性都可支援其唯讀屬性所定義的一或多個行事曆 CultureInfo.OptionalCalendarsEach culture may support one or more calendars defined by its read-only CultureInfo.OptionalCalendars property. 特定物件目前使用的行事曆 CultureInfo 是由其屬性定義 DateTimeFormatInfo.CalendarThe calendar currently used by a specific CultureInfo object is defined by its DateTimeFormatInfo.Calendar property. 它必須是在陣列中找到的其中一個行事曆 CultureInfo.OptionalCalendarsIt 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. 例如,泰文曆文化特性的預設行事曆是由類別代表的泰文曆紀元行事曆 ThaiBuddhistCalendarFor example, the default calendar of the Thai Buddhist culture is the Thai Buddhist Era calendar, which is represented by the ThaiBuddhistCalendar class. CultureInfo 日期和時間格式設定作業中使用代表泰文泰文化特性的物件時,預設會使用泰文泰年代行事曆。When a CultureInfo object that represents the Thai Buddhist culture is used in a date and time formatting operation, the Thai Buddhist Era calendar is used by default. 只有當文化特性的屬性變更時,才會使用西曆 DateTimeFormatInfo.Calendar ,如下列範例所示:The Gregorian calendar is used only if the culture's DateTimeFormatInfo.Calendar property is changed, as the following example shows:

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

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

Console.WriteLine(value.ToString(thTH))

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

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

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

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

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

您可以 DateTime 使用日期和時間專案來將值具現化,方法是呼叫包含參數的日期 時間 函式,並 calendar 將代表該行事曆的物件傳遞給它,以使用特定行事曆的年、月和日) (數目 CalendarYou 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. 下列範例會使用行事曆的日期和時間元素 ThaiBuddhistCalendarThe following example uses the date and time elements from the ThaiBuddhistCalendar calendar.

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

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

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

所有其他 DateTime 屬性和方法都使用西曆。All other DateTime properties and methods use the Gregorian calendar. 例如, DateTime.Year 屬性會傳回西曆中的年份,而此 DateTime.IsLeapYear(Int32) 方法 year 會假設參數是西曆中的年份。For example, the DateTime.Year property returns the year in the Gregorian calendar, and the DateTime.IsLeapYear(Int32) method assumes that the year parameter is a year in the Gregorian calendar. 每個 DateTime 使用西曆的成員都有一個使用特定行事曆之類別的對應成員 CalendarEach DateTime member that uses the Gregorian calendar has a corresponding member of the Calendar class that uses a specific calendar. 例如,方法會傳回 Calendar.GetYear 特定行事曆中的年份,而此方法會將 Calendar.IsLeapYear year 參數視為特定行事曆中的年份號碼。For example, the Calendar.GetYear method returns the year in a specific calendar, and the Calendar.IsLeapYear method interprets the year parameter as a year number in a specific calendar. 下列範例會使用 DateTime 和類別的對應成員 ThaiBuddhistCalendarThe following example uses both the DateTime and the corresponding members of the ThaiBuddhistCalendar class.

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

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

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

DateTime結構包含的 DayOfWeek 屬性會傳回西曆中的星期幾。The DateTime structure includes a DayOfWeek property that returns the day of the week in the Gregorian calendar. 它不包含可讓您取出年度周數的成員。It does not include a member that allows you to retrieve the week number of the year. 若要取出一年中的周,請呼叫個別行事曆的 Calendar.GetWeekOfYear 方法。To retrieve the week of the year, call the individual calendar's Calendar.GetWeekOfYear method. 下列範例提供一個實例。The following example provides an illustration.

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

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

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

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

保存日期時間值Persisting DateTime values

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

DateTime無論您選擇哪一種技術,您都必須確定還原值的常式不會遺失資料或擲回例外狀況。You must ensure that the routine that restores the DateTime values doesn't lose data or throw an exception regardless of which technique you choose. DateTime 值應該是來回行程。DateTime values should round-trip. 也就是說,原始值和還原的值應該相同。That is, the original value and the restored value should be the same. 而且,如果原始 DateTime 值代表一段時間,它應該會在還原時識別相同的時間點。And if the original DateTime value represents a single instant of time, it should identify the same moment of time when it's restored.

將值保存為字串Persisting values as strings

若要成功還原 DateTime 保存為字串的值,請遵循下列規則:To successfully restore DateTime values that are persisted as strings, follow these rules:

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

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

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

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

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

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

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

  1. 如果這些值代表一段時間,請呼叫方法,將它們從當地時間轉換成 UTC ToUniversalTimeIf the values represent single moments of time, convert them from the local time to UTC by calling the ToUniversalTime method.
  2. 藉由呼叫或多載,將日期轉換為其字串表示 ToString(String, IFormatProvider) String.Format(IFormatProvider, String, Object[])Convert the dates to their string representations by calling the ToString(String, IFormatProvider) or String.Format(IFormatProvider, String, Object[]) overload. 藉由指定 CultureInfo.InvariantCulture 做為引數,來使用不因文化特性而異的格式慣例 providerUse 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 TryParseExactParse the data by calling the ParseExact or TryParseExact overload. 指定 CultureInfo.InvariantCulture 做為 provider 引數,並使用您在轉換期間用於引數的相同標準格式字串 formatSpecify CultureInfo.InvariantCulture as the provider argument, and use the same standard format string you used for the format argument during conversion. DateTimeStyles.RoundtripKind在引數中包含值 stylesInclude the DateTimeStyles.RoundtripKind value in the styles argument.
  2. 如果這些 DateTime 值代表一分鐘的時間,請呼叫方法,將剖析 ToLocalTime 的日期從 UTC 轉換為當地時間。If the DateTime values represent single moments in time, call the ToLocalTime method to convert the parsed date from UTC to local time.

下列範例會使用不因文化特性而異的文化特性和 "O" 標準格式字串,以確保 DateTime 儲存和還原的值都代表相同的時間點,而不論來源和目標系統的系統、文化特性或時區為何。The following example uses the invariant culture and the "O" standard format string to ensure that DateTime values saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems.

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

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

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

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

Private Sub RestoreDatesAsInvariantStrings()
    TimeZoneInfo.ClearCachedData()
    Console.WriteLine("Current Time Zone: {0}",
                    TimeZoneInfo.Local.DisplayName)
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB")
    Dim sr As New StreamReader(filenameTxt)
    Dim inputValues As String() = sr.ReadToEnd().Split({"|"c}, StringSplitOptions.RemoveEmptyEntries)
    sr.Close()
    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each inputValue In inputValues
        Dim dateValue As Date
        If DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture,
                          DateTimeStyles.RoundtripKind, dateValue) Then
            Console.WriteLine($"'{inputValue}' --> {dateValue.ToLocalTime():f}")
        Else
            Console.WriteLine($"Cannot parse '{inputValue}'")
        End If
    Next
    Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
'       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
'       The dates on an en-US system:
'       Saturday, June 14, 2014 6:32 AM
'       Thursday, July 10, 2014 11:49 PM
'       Saturday, January 10, 2015 1:16 AM
'       Saturday, December 20, 2014 9:45 PM
'       Monday, June 02, 2014 3:14 PM
'       Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
'       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
'       The dates on an en-GB system:
'       '2014-06-14T13:32:00.0000000Z' --> 14 June 2014 14:32
'       '2014-07-11T06:49:00.0000000Z' --> 11 July 2014 07:49
'       '2015-01-10T09:16:00.0000000Z' --> 10 January 2015 09:16
'       '2014-12-21T05:45:00.0000000Z' --> 21 December 2014 05:45
'       '2014-06-02T22:14:00.0000000Z' --> 02 June 2014 23:14
'       Restored dates...
將值保存為整數Persisting values as integers

您可以將日期和時間保存為 Int64 代表刻度數目的值。You can persist a date and time as an Int64 value that represents a number of ticks. 在這種情況下,您不需要考慮系統的文化特性,這些 DateTime 值會在上保存和還原。In this case, you don't have to consider the culture of the systems the DateTime values are persisted and restored on.

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

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

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

  1. 藉由將值傳遞至函式,以具現化新的 DateTime 物件 Int64 DateTime(Int64)Instantiate a new DateTime object by passing the Int64 value to the DateTime(Int64) constructor.
  2. 如果 DateTime 值代表一段時間,請呼叫方法,將其從 UTC 轉換為當地時間 ToLocalTimeIf the DateTime value represents a single moment in time, convert it from UTC to the local time by calling the ToLocalTime method.

下列範例會將值陣列保存 DateTime 為美國太平洋時區系統上的整數。The following example persists an array of DateTime values as integers on a system in the U.S. Pacific Time zone. 它會在 UTC 區域的系統上進行還原。It restores it on a system in the UTC zone. 包含整數的檔案包含 Int32 值,表示緊接在其後的 Int64 值總數。The file that contains the integers includes an Int32 value that indicates the total number of Int64 values that immediately follow it.

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

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

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

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

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

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

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

    Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each value In dates
        Console.WriteLine(value.ToString("f"))
    Next
    Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
'       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
'       The dates on an en-US system:
'       Saturday, June 14, 2014 6:32 AM
'       Thursday, July 10, 2014 11:49 PM
'       Saturday, January 10, 2015 1:16 AM
'       Saturday, December 20, 2014 9:45 PM
'       Monday, June 02, 2014 3:14 PM
'       Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
'       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
'       The dates on an en-GB system:
'       14 June 2014 14:32
'       11 July 2014 07:49
'       10 January 2015 09:16
'       21 December 2014 05:45
'       02 June 2014 23:14
'       Restored dates...

序列化 DateTime 值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,再藉由呼叫方法將它序列化 ToUniversalTimeIf a DateTime value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the ToUniversalTime method. 將它還原序列化之後,請呼叫方法,將它從 UTC 轉換為當地時間 ToLocalTimeAfter you deserialize it, convert it from UTC to local time by calling the ToLocalTime method. 下列範例會使用 BinaryFormatter 類別來序列化 DateTime 美國太平洋標準時區系統上的資料,並在美國中部標準區域的系統上將其還原序列化。The following example uses the BinaryFormatter class to serialize DateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the U.S. Central Standard zone.

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

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

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

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

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

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

    Console.WriteLine("The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:")
    For Each value In dates
        Console.WriteLine(value.ToLocalTime().ToString("f"))
    Next
    Console.WriteLine("Restored dates...")
End Sub
' When saved on an en-US system, the example displays the following output:
'       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
'       The dates on an en-US system:
'       Saturday, June 14, 2014 6:32 AM
'       Thursday, July 10, 2014 11:49 PM
'       Saturday, January 10, 2015 1:16 AM
'       Saturday, December 20, 2014 9:45 PM
'       Monday, June 02, 2014 3:14 PM
'       Saved dates...
'
' When restored on an en-GB system, the example displays the following output:
'       Current Time Zone: (UTC-6:00) Central Time (US & Canada)
'       The dates on an en-GB system:
'       14 June 2014 08:32
'       11 July 2014 01:49
'       10 January 2015 03:16
'       20 December 2014 11:45
'       02 June 2014 17:14
'       Restored dates...

序列化日期時間和時區資料Serializing DateTime and time zone data

上述範例全都假設 DateTime 值會以當地時程表示。The previous examples all assumed that DateTime values are expressed as local times. 程式碼會在 UTC 和本地時間之間轉換值,以便在來源與目標系統上反映相同的時間點。The code converted the values between UTC and local time so they reflect the same moment in time on the source and target systems. DateTime 值也可能反映本機和 UTC 以外時區的時間。DateTime values may also reflect moments in time in a time zone other than local and UTC. 因為 DateTime 結構不是時區感知,所以您必須將 DateTime 值和 TimeZoneInfo 代表其時區的物件序列化。Because the DateTime structure is not time zone-aware, you have to serialize both the DateTime value and the TimeZoneInfo object that represents its time zone. 建立一種類型,其欄位包含 DateTime 值和其時區。Create a type whose fields include both the DateTime value and its time zone. 下列範例會定義 DateWithTimeZone 結構。The following example defines a DateWithTimeZone structure.

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

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

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

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

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

重要

DateWithTimeZone結構會在接下來的兩個範例中使用,這兩個範例會將物件陣列序列化和還原序列化 DateWithTimeZoneThe DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. 您可以從 GitHub 上的檔存放庫中的 Visual Basicc # ,查看本文中整組範例的來源。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 類別來序列化物件的陣列 DateWithTimeZoneThe following example uses the BinaryFormatter class to serialize an array of DateWithTimeZone objects.

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

然後,下列範例會呼叫 BinaryFormatter.Deserialize 方法將其還原序列化。The following example then calls the BinaryFormatter.Deserialize method to deserialize it.

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

    var formatter = new BinaryFormatter();
    DateWithTimeZone[] dates;
    try
    {
        dates = (DateWithTimeZone[])formatter.Deserialize(fs);
        // Display dates.
        foreach (var date in dates)
        {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine($"{ date.DateTime} {(tz.IsDaylightSavingTime(date.DateTime) ? tz.DaylightName : tz.StandardName)}");
        }
    }
    catch (SerializationException e)
    {
        Console.WriteLine($"Deserialization failed. Reason: {e.Message}");
    }
    finally
    {
        if (fs != null) fs.Close();
    }
}
// The example displays the following output:
//       8/9/2014 7:30:00 PM Eastern Daylight Time
//       8/15/2014 7:00:00 PM Pacific Daylight Time
//       8/22/2014 7:30:00 PM Eastern Daylight Time
//       8/28/2014 7:00:00 PM Eastern Daylight Time
Public Sub RestoreDateWithTimeZone()
    Dim fs As FileStream
    If File.Exists(filename) Then
        fs = New FileStream(filename, FileMode.Open)
    Else
        Console.WriteLine("Unable to find file to deserialize.")
        Exit Sub
    End If

    Dim formatter As New BinaryFormatter()
    Dim dates As DateWithTimeZone ()= Nothing
    Try
        dates = DirectCast(formatter.Deserialize(fs), DateWithTimeZone())
        ' Display dates.
        For Each dateInfo In dates
            Dim tz As TimeZoneInfo = dateInfo.TimeZone
            Console.WriteLine($"{dateInfo.DateTime} {If(tz.IsDaylightSavingTime(dateInfo.DateTime), tz.DaylightName, tz.StandardName)}")
        Next
    Catch e As SerializationException
        Console.WriteLine("Deserialization failed. Reason: {e.Message}")
    Finally
        If fs IsNot Nothing Then fs.Close()
    End Try
End Sub
' The example displays the following output:
'       8/9/2014 7:30:00 PM Eastern Daylight Time
'       8/15/2014 7:00:00 PM Pacific Daylight Time
'       8/22/2014 7:30:00 PM Eastern Daylight Time
'       8/28/2014 7:00:00 PM Eastern Daylight Time

DateTime 與 TimeSpanDateTime vs. TimeSpan

DateTimeTimeSpan 數值型別不同之處在于, DateTime 代表時間的瞬間,而 TimeSpan 代表時間間隔。The DateTime and TimeSpan value types differ in that a DateTime represents an instant in time whereas a TimeSpan represents a time interval. 您可以從另一個實例減去一個實例, DateTime 以取得 TimeSpan 代表兩者之間時間間隔的物件。You can subtract one instance of DateTime from another to obtain a TimeSpan object that represents the time interval between them. 或者,您可以在目前的中加入一個正數, TimeSpan DateTime 以取得 DateTime 代表未來日期的值。Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date.

您可以從物件中新增或減少時間間隔 DateTimeYou can add or subtract a time interval from a DateTime object. 時間間隔可以是負數或正數,也可以用刻度、秒數等單位來表示,或以物件表示 TimeSpanTime intervals can be negative or positive, and they can be expressed in units such as ticks, seconds, or as a TimeSpan object.

比較容錯內的相等Comparing for equality within tolerance

值的相等比較 DateTime 是精確的。Equality comparisons for DateTime values are exact. 這表示兩個值必須以相同的刻度數目表示,以視為相等。That means two values must be expressed as the same number of ticks to be considered equal. 對於許多應用程式而言,精確度通常是不必要或甚至不正確的。That precision is often unnecessary or even incorrect for many applications. 通常,您會想要測試 DateTime 物件是否 大致相等Often, you want to test if DateTime objects are roughly equal.

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

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

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

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

    Return Math.Abs(delta) < windowInSeconds
End Function

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

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

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

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

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

COM interop 考慮COM interop considerations

DateTime傳送至 COM 應用程式的值,然後傳回至受控應用程式,稱為「往返」。A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. 但是, DateTime 只指定時間的值並不會如您預期般地往返。However, a DateTime value that specifies only a time does not round-trip as you might expect.

如果您只反復存取一段時間(例如下午3點),則最終日期和時間是1899年12月30日If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. 在下午3:00,而非西元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 則會假設西元1月1日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 只指定時間,您的應用程式就必須記得修改或忽略最後一個物件中的錯誤日期 DateTimeThe behavior of the .NET Framework and COM means that if your application round-trips a DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final DateTime object.

建構函式

DateTime(Int32, Int32, Int32)

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

DateTime(Int32, Int32, Int32, Calendar)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DateTime(Int64)

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

DateTime(Int64, DateTimeKind)

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

欄位

MaxValue

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

MinValue

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

UnixEpoch

這個常數的值相當於西曆中的國際標準時間 00:00:00.0000000,1970 年 1 月 1 日。The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 1970, in the Gregorian calendar. UnixEpoch 定義 UNIX 時間等於 0 的時間點。UnixEpoch defines the point in time when Unix time is equal to 0.

屬性

Date

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

Day

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

DayOfWeek

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

DayOfYear

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

Hour

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

Kind

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

Millisecond

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

Minute

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

Month

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

Now

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

Second

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

Ticks

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

TimeOfDay

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

Today

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

UtcNow

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

Year

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

方法

Add(TimeSpan)

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

AddDays(Double)

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

AddHours(Double)

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

AddMilliseconds(Double)

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

AddMinutes(Double)

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

AddMonths(Int32)

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

AddSeconds(Double)

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

AddTicks(Int64)

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

AddYears(Int32)

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

Compare(DateTime, DateTime)

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

CompareTo(DateTime)

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

CompareTo(Object)

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

DaysInMonth(Int32, Int32)

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

Equals(DateTime)

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

Equals(DateTime, DateTime)

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

Equals(Object)

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

FromBinary(Int64)

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

FromFileTime(Int64)

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

FromFileTimeUtc(Int64)

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

FromOADate(Double)

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

GetDateTimeFormats()

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

GetDateTimeFormats(Char)

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

GetDateTimeFormats(Char, IFormatProvider)

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

GetDateTimeFormats(IFormatProvider)

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

GetHashCode()

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

GetTypeCode()

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

IsDaylightSavingTime()

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

IsLeapYear(Int32)

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

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

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

Parse(String)

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

Parse(String, IFormatProvider)

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

Parse(String, IFormatProvider, DateTimeStyles)

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

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

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span 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(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles)

使用指定格式、特定文化特性格式資訊以及樣式的陣列,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span 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.

ParseExact(String, String, IFormatProvider)

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

ParseExact(String, String, IFormatProvider, DateTimeStyles)

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

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

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

SpecifyKind(DateTime, DateTimeKind)

建立新的 DateTime 物件,此物件的刻度數與指定的 DateTime 相同,但依指定的 DateTimeKind 值所示,指定為本地時間、國際標準時間 (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)

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

Subtract(TimeSpan)

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

ToBinary()

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

ToFileTime()

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

ToFileTimeUtc()

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

ToLocalTime()

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

ToLongDateString()

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

ToLongTimeString()

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

ToOADate()

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

ToShortDateString()

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

ToShortTimeString()

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

ToString()

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

ToString(IFormatProvider)

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

ToString(String)

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

ToString(String, IFormatProvider)

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

ToUniversalTime()

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

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

嘗試將目前日期時間執行個體的值格式化為所提供字元範圍。Tries to format the value of the current datetime instance into the provided span of characters.

TryParse(ReadOnlySpan<Char>, DateTime)

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

TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)

使用指定的特定文化特性格式資訊和格式樣式,以將日期和時間的範圍表示轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。Converts the span 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(String, DateTime)

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

TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

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

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles, DateTime)

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTimeConverts the specified span 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(ReadOnlySpan<Char>, String[], IFormatProvider, DateTimeStyles, DateTime)

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

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

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

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

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

運算子

Addition(DateTime, TimeSpan)

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

Equality(DateTime, DateTime)

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

GreaterThan(DateTime, DateTime)

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

GreaterThanOrEqual(DateTime, DateTime)

判斷某個指定之 DateTime 表示的是同於還是晚於另一個指定之 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)

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

LessThan(DateTime, DateTime)

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

LessThanOrEqual(DateTime, DateTime)

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

Subtraction(DateTime, DateTime)

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

Subtraction(DateTime, TimeSpan)

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

明確介面實作

IComparable.CompareTo(Object)

將目前的執行個體與相同類型的另一個物件相比較,並傳回整數,這個整數表示目前的執行個體在排序次序中,位於另一個物件之前、之後或相同位置。Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

IConvertible.GetTypeCode()

傳回這個執行個體的 TypeCodeReturns the TypeCode for this instance.

IConvertible.ToBoolean(IFormatProvider)

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

IConvertible.ToByte(IFormatProvider)

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

IConvertible.ToChar(IFormatProvider)

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

IConvertible.ToDateTime(IFormatProvider)

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

IConvertible.ToDecimal(IFormatProvider)

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

IConvertible.ToDouble(IFormatProvider)

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

IConvertible.ToInt16(IFormatProvider)

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

IConvertible.ToInt32(IFormatProvider)

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

IConvertible.ToInt64(IFormatProvider)

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

IConvertible.ToSByte(IFormatProvider)

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

IConvertible.ToSingle(IFormatProvider)

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

IConvertible.ToType(Type, IFormatProvider)

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

IConvertible.ToUInt16(IFormatProvider)

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

IConvertible.ToUInt32(IFormatProvider)

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

IConvertible.ToUInt64(IFormatProvider)

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

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

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

適用於

執行緒安全性

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

另請參閱