DateTime DateTime DateTime DateTime Struct

定義

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

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

備註

重要

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

注意

本文中的 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。The C# examples in this article run in the Try.NET inline code runner and playground. 選取 [執行] 按鈕以在互動式視窗中執行範例。Select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

Try.NET 內嵌程式碼執行器與 Playground 的當地時區是全球標準時間 (UTC)。The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. 這可能會影響示範 DateTimeDateTimeOffsetTimeZoneInfo 型別與其成員之範例的行為與輸出。This may affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.

這篇文章包含數個範例,使用DateTime類型:This article includes several examples that use the DateTime type:

初始化範例Initialization Examples

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

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

DateTime 解決方式DateTime resolution

文化特性和行事曆Culture and calendars

持續性Persistence

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

DateTime實值型別代表日期和時間的值範圍是 00:00:00 (午夜),1 月 1 日 0001 P.m (中古時代) 下午 11:59:59,透過年 12 月 31 到西元 9999年日The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)西曆。(C.E.) in the Gregorian calendar.

時間值是以 100 奈秒為單位,稱為刻度為單位。Time values are measured in 100-nanosecond units called ticks. 特定日期是午夜 12:00,年 1 月 1,西元 0001年的刻度數A particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.)在 GregorianCalendar行事曆。(C.E.) in the GregorianCalendar calendar. 數字會排除刻度將會新增閏秒。The number excludes ticks that would be added by leap seconds. 比方說,31241376000000000l 刻度值代表 0100 年 1 月 01,星期五的日期午夜 12:00:00。For example, a ticks value of 31241376000000000L represents the date Friday, January 01, 0100 12:00:00 midnight. ADateTime值一律表示在內容明確或預設的行事曆。A DateTime value is always expressed in the context of an explicit or default calendar.

注意

如果您正在使用刻度值,您想要轉換成某些其他時間間隔,例如分鐘或秒,您應該使用TimeSpan.TicksPerDayTimeSpan.TicksPerHourTimeSpan.TicksPerMinuteTimeSpan.TicksPerSecond,或TimeSpan.TicksPerMillisecond常數,以執行轉換。If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the TimeSpan.TicksPerDay, TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.TicksPerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. 例如,若要新增的秒數表示所指定的刻度數Second元件DateTime的值,您可以使用運算式dateValue.Second + nTicks/Timespan.TicksPerSecondFor example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.

您可以在檢視這篇文章中的範例整組的來源Visual Basic或是C#從 GitHub 上的 docs 存放庫。You can view the source for the entire set of examples from this article in either Visual Basic or C# from the docs repository on GitHub.

注意

替代DateTime結構,使用日期和時間值特別時區是DateTimeOffset結構。An alternative to the DateTime structure for working with date and time values in particular time zones is the DateTimeOffset structure. DateTimeOffset結構會將日期和時間資訊儲存在私人DateTime欄位並供該日期和時間的分鐘數與 UTC 差異在私人Int16欄位。The DateTimeOffset structure stores date and time information in a private DateTime field and the number of minutes by which that date and time differs from UTC in a private Int16 field. 這可讓DateTimeOffset值,以反映特定時區的時間,而DateTime僅 UTC 和當地時區的時間,值可以明確地反映。This makes it possible for a DateTimeOffset value to reflect the time in a particular time zone, whereas a DateTime value can unambiguously reflect only UTC and the local time zone's time. 如需使用時機的討論DateTime結構或DateTimeOffset結構處理日期和時間值時,請參閱選擇 DateTime、 DateTimeOffset、 TimeSpan 和 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 default constructor.
  • 指派DateTime屬性或方法的傳回值。Assigning a DateTime to the return value of a property or method.
  • 剖析DateTime從其字串表示法的值。Parsing a DateTime value from its string representation.
  • 使用 Visual Basic 特定的語言功能來具現化DateTimeUsing Visual Basic-specific language features to instantiate a DateTime.

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

叫用建構函式Invoke Constructors

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

Dim date1 As New Date(2008, 5, 1, 8, 30, 52)
DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
Console.WriteLine(date1);

您可以叫用DateTime結構的隱含預設建構函式時要DateTime初始化為其預設值。You invoke the DateTime structure's implicit default constructor when you want a DateTime initialized to its default value. (如需實值類型的隱含預設建構函式的詳細資訊,請參閱實值型別。)某些編譯器也支援宣告DateTime而不需要明確地將值指派給它的值。(For details on the implicit default constructor of a value type, see Value Types.) Some compilers also support declaring a DateTime value without explicitly assigning a value to it. 建立沒有明確的初始設定的值也會產生預設值。Creating a value without an explicit initialization also results in the default value. 下列範例說明DateTimeC# 和 Visual Basic 中的隱含預設建構函式以及DateTime宣告未在 Visual Basic 中的指派。The following example illustrates the DateTime implicit default constructor in C# and Visual Basic, as well as a DateTime declaration without assignment in Visual Basic.

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))
DateTime dat1 = new DateTime();
// The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
// The following method call displays True.
Console.WriteLine(dat1.Equals(DateTime.MinValue));
將計算的值指派給Assigning a computed value

您可以指派DateTime物件的屬性或方法所傳回的日期和時間值。You can assign the DateTime object a date and time value returned by a property or method. 下列範例會指派目前的日期和時間、 目前的 Coordinated Universal Time (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.

Dim date1 As Date = Date.Now
Dim date2 As Date = Date.UtcNow
Dim date3 As Date = Date.Today
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.UtcNow;
DateTime date3 = DateTime.Today;
剖析字串,表示為 DateTimeParsing a string that represents a DateTime

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

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

string dateString = "5/1/2008 8:30:52 AM";
DateTime date1 = DateTime.Parse(dateString,
                          System.Globalization.CultureInfo.InvariantCulture);
string 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.

Dim date1 As Date = #5/1/2008 8:30:52AM#

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

就內部而言,所有DateTime值會表示為 0001 年 1 月 1 日的 12:00:00 午夜起已經過的刻度 (100 奈秒間隔數) 的數目。Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. 實際DateTime值無關的方式顯示時,出現的值。The actual DateTime value is independent of the way in which that value appears when displayed. 外觀DateTime值是一種將值轉換為其字串表示的格式化作業的結果。The appearance of a DateTime value is the result of a formatting operation that converts a value to its string representation.

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

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

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

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

DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F"));
// Displays Saturday, March 01, 2008 7:00:00 AM
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.

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

DateTime.ToString(String)多載也可用以自訂格式字串來指定其他格式。The DateTime.ToString(String) overload can also be used with a custom format string to specify other formats. 下列範例示範如何格式化字串,使用ISO 8601通常用於 web 服務的標準格式。The following example shows how to format a string using the ISO 8601 standard format often used for web services. Iso 8601 格式並沒有對應的標準格式字串。The Iso 8601 format does not have a corresponding standard format string.

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

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

如需有關格式化DateTime值,請參閱標準日期和時間格式字串自訂日期和時間格式字串For more information about formatting DateTime values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

從字串剖析的日期時間值Parsing DateTime values from strings

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

  • 日期和時間會以各種形式,並反映目前文化特性或特定文化特性的慣例。A date and time takes a variety of forms and reflects the conventions of either the current culture or a specific culture. 例如,應用程式可讓其目前的文化特性是 EN-US 輸入日期值為"12/15/2013 」 或 「 2013 年 12 月 15 日 」 的使用者。For example, an application allows a user whose current culture is en-US to input a date value as "12/15/2013" or "December 15, 2013". 它可讓的使用者,其目前的文化特性是 en-us gb 輸入日期值做為 「 15/12/2013 」 或 「 15 2013 年 12 月 」。It allows a user whose current culture is en-gb to input a date value as "15/12/2013" or "15 December 2013."

  • 以預先定義的格式表示的日期和時間。A date and time is represented in a predefined format. 比方說,應用程式將序列化為 「 20130103"獨立於其執行應用程式的文化特性的日期。For example, an application serializes a date as "20130103" independently of the culture on which the app is running. 應用程式可能需要目前文化特性的簡短日期格式輸入日期。An application may require dates be input in the current culture's short date format.

您使用Parse或是TryParse方法,將字串轉換其中一個文化特性所使用的常見的日期和時間格式DateTime值。You use the Parse or TryParse method to convert a string from one of the common date and time formats used by a culture to a DateTime value. 下列範例示範如何使用TryParse要轉換至不同的文化特性特定格式的日期字串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");

DateTime date1 = new DateTime(2013, 6, 1, 12, 32, 30);
List<string> 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 DateTime = 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.

string[] formats = { "yyyyMMdd", "HHmmss" };
string[] dateStrings = { "20130816", "20131608", "  20130816   ",
                   "115216", "521116", "  115216  " };
DateTime parsedDate;

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

string 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. 您應該使用TryParseTryParseExact效能很重要的案例中的方法。You should use the TryParse or TryParseExact methods in scenarios where performance is important. 日期和時間字串的剖析作業通常具有高失敗率,而且例外狀況處理費用昂貴。The parsing operation for date and time strings tends to have a high failure rate, and exception handling is expensive. 如果字串輸入的使用者,請使用這些方法,或來自未知來源。Use these methods if strings are input by users or coming from an unknown source.

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

日期時間值DateTime values

中的時間值的描述DateTime類型通常會使用 Coordinated Universal Time (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). Coordinated Universal Time 不為零的度經度,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屬性所表示日期和時間值秒的一個 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方法會導入了 5 毫秒的延遲。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結構,例如AddSubtract,不會修改結構的值。A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. 相反地,計算會傳回新DateTime結構,其值是計算的結果。Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.

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

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

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

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

作業所使用的成員DateTime類型納入帳戶詳細資料,例如潤年和在月份的天數。Operations by members of the DateTime type take into account details such as leap years and the number of days in a month.

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

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

重要

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

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

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

var thTH = new System.Globalization.CultureInfo("th-TH");
var value = new DateTime(2016, 5, 28);

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

thTH.DateTimeFormat.Calendar = new System.Globalization.GregorianCalendar();
Console.WriteLine(value.ToString(thTH));
// Press "Run" to see the output
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.

var thTH = new System.Globalization.CultureInfo("th-TH");
var value = DateTime.Parse("28/05/2559", thTH);
Console.WriteLine(value.ToString(thTH));

thTH.DateTimeFormat.Calendar = new System.Globalization.GregorianCalendar();
Console.WriteLine(value.ToString(thTH));
// Press "Run" to see the output
Private Sub ThaiBuddhistEraParse()
    Dim thTH As New CultureInfo("th-TH")
    Dim value As DateTime = DateTime.Parse("28/5/2559", thTH)
    Console.WriteLine(value.ToString(thTH))

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

您具現化DateTime值使用藉由呼叫的日期和時間的項目 (年、 月和日的數目) 在特定行事曆DateTime 建構函式包含calendar參數,並將其傳遞Calendar物件,表示該月曆。You instantiate a DateTime value using the date and time elements (number of the year, month, and day) of a specific calendar by calling a DateTime constructor that includes a calendar parameter and passing it a Calendar object that represents that calendar. 下列範例使用的日期和時間的項目從ThaiBuddhistCalendar行事曆。The following example uses the date and time elements from the ThaiBuddhistCalendar calendar.

var thTH = new System.Globalization.CultureInfo("th-TH");
var dat = new DateTime(2559, 5, 28, thTH.DateTimeFormat.Calendar);
Console.WriteLine($"Thai Buddhist era date: {dat.ToString("d", thTH)}");
Console.WriteLine($"Gregorian date:   {dat:d}");
// Press "Run" to see the output
Dim thTH As New CultureInfo("th-TH")
Dim dat As New DateTime(2559, 5, 28, thTH.DateTimeFormat.Calendar)
Console.WriteLine("Thai Buddhist Era date: {0}", dat.ToString("d", thTH))
Console.WriteLine("Gregorian date:   {0:d}", dat)
' The example displays the following output:
'       Thai Buddhist Era Date:  28/5/2559
'       Gregorian Date:     28/05/2016

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

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

var thTH = new System.Globalization.CultureInfo("th-TH");
var cal = thTH.DateTimeFormat.Calendar;
var dat = 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))}\n");

Console.WriteLine("Using the Gregorian calendar:");
Console.WriteLine($"Date: {dat:d}");
Console.WriteLine($"Year: {dat.Year}");
Console.WriteLine($"Leap year: {DateTime.IsLeapYear(dat.Year)}");
// Press "Run" to see the output
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: {0}", dat.ToString("d", thTH))
Console.WriteLine("Year: {0}", cal.GetYear(dat))
Console.WriteLine("Leap year: {0}", cal.IsLeapYear(cal.GetYear(dat)))
Console.WriteLine()

Console.WriteLine("Using the Gregorian calendar:")
Console.WriteLine("Date: {0:d}", dat)
Console.WriteLine("Year: {0}", dat.Year)
Console.WriteLine("Leap year: {0}", DateTime.IsLeapYear(dat.Year))
' The example displays the following output:
'       Using the 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.

var thTH = new System.Globalization.CultureInfo("th-TH");
var thCalendar = thTH.DateTimeFormat.Calendar;
var dat = 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, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}\n");

var greg = new System.Globalization.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, System.Globalization.CalendarWeekRule.FirstDay,DayOfWeek.Sunday)}");
// Press "Run" to see the output
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: {0}", dat.ToString("d", thTH))
Console.WriteLine("Day of Week: {0}", thCalendar.GetDayOfWeek(dat))
Console.WriteLine("Week of year: {0}",
                thCalendar.GetWeekOfYear(dat, CalendarWeekRule.FirstDay,
                                       DayOfWeek.Sunday))
Console.WriteLine()

Dim greg As Calendar = New GregorianCalendar()
Console.WriteLine("Using the Gregorian calendar:")
Console.WriteLine("Date: {0:d}", dat)
Console.WriteLine("Day of Week: {0}", dat.DayOfWeek)
Console.WriteLine("Week of year: {0}",
                 greg.GetWeekOfYear(dat, CalendarWeekRule.FirstDay,
                                    DayOfWeek.Sunday))
' The example displays the following output:
'       Using the 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.

public static void PersistAsLocalStrings()
{
    SaveLocalDatesAsString();
    RestoreLocalDatesFromString();
}

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

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

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

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

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

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

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

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

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

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

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

public static void PersistAsInvariantStrings()
{
    SaveDatesAsInvariantStrings();
    RestoreDatesAsInvariantStrings();
}

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

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

private static void RestoreDatesAsInvariantStrings()
{
    TimeZoneInfo.ClearCachedData();
    Console.WriteLine("Current Time Zone: {0}",
                      TimeZoneInfo.Local.DisplayName);
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
    StreamReader sr = new StreamReader(filenameTxt);
    string[] inputValues = sr.ReadToEnd().Split(new char[] { '|' },
                                                StringSplitOptions.RemoveEmptyEntries);
    sr.Close();
    Console.WriteLine("The dates on an {0} system:",
                      Thread.CurrentThread.CurrentCulture.Name);
    foreach (var inputValue in inputValues)
    {
        DateTime dateValue;
        if (DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture,
                              DateTimeStyles.RoundtripKind, out dateValue))
        {
            Console.WriteLine($"'{inputValue}' --> {dateValue.ToLocalTime():f}");
        }
        else
        {
            Console.WriteLine("Cannot parse '{0}'", inputValue);
        }
    }
    Console.WriteLine("Restored dates...");
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC) Dublin, Edinburgh, Lisbon, London
//       The dates on an en-GB system:
//       '2014-06-14T13:32:00.0000000Z' --> 14 June 2014 14:32
//       '2014-07-11T06:49:00.0000000Z' --> 11 July 2014 07:49
//       '2015-01-10T09:16:00.0000000Z' --> 10 January 2015 09:16
//       '2014-12-21T05:45:00.0000000Z' --> 21 December 2014 05:45
//       '2014-06-02T22:14:00.0000000Z' --> 02 June 2014 23:14
//       Restored dates...
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值代表單一時間的藉由呼叫將它們轉換成 UTCToUniversalTime方法。If the DateTime values represent single moments in time, convert them to UTC by calling the ToUniversalTime method.
  • 擷取的數字所表示之刻度DateTime值從其Ticks屬性。Retrieve the number of ticks represented by the DateTime value from its Ticks property.

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

  1. 新具現化DateTime物件,並傳遞Int64DateTime(Int64)建構函式。Instantiate a new DateTime object by passing the Int64 value to the DateTime(Int64) constructor.
  2. 如果DateTime值代表單一時間點,它從 UTC 轉換為當地時間藉由呼叫ToLocalTime方法。If the DateTime value represents a single moment in time, convert it from UTC to the local time by calling the ToLocalTime method.

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

public static void PersistAsIntegers()
{
    SaveDatesAsInts();
    RestoreDatesAsInts();
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

序列化的日期時間值Serializing DateTime values

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

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

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

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

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

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

    // Display the dates.
    Console.WriteLine($"Leap year days from 2000-2100 on an {Thread.CurrentThread.CurrentCulture.Name} system:");
    int nItems = 0;
    foreach (var dat in deserializedDates)
    {
        Console.Write($"   {dat:d}     ");
        nItems++;
        if (nItems % 5 == 0)
            Console.WriteLine();
    }
}
// The example displays the following output:
//    Leap year days from 2000-2100 on an en-GB system:
//       29/02/2000       29/02/2004       29/02/2008       29/02/2012       29/02/2016
//       29/02/2020       29/02/2024       29/02/2028       29/02/2032       29/02/2036
//       29/02/2040       29/02/2044       29/02/2048       29/02/2052       29/02/2056
//       29/02/2060       29/02/2064       29/02/2068       29/02/2072       29/02/2076
//       29/02/2080       29/02/2084       29/02/2088       29/02/2092       29/02/2096
Public Sub PersistAsXml()
    ' Serialize the data.
    Dim leapYears As New List(Of DateTime)()
    For year As Integer = 2000 To 2100 Step 4
        If Date.IsLeapYear(year) Then
            leapYears.Add(New Date(year, 2, 29))
        End If
    Next
    Dim dateArray() As DateTime = leapYears.ToArray()

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

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

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

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

前一個範例不包含時間資訊。The previous example doesn't include time information. 如果DateTime值代表時間點,而且以本地時間表示,將它轉換從當地時間與 UTC 序列化藉由呼叫之前ToUniversalTime方法。If a DateTime value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the ToUniversalTime method. 將它還原序列化之後,它從 UTC 轉換為當地時間藉由呼叫ToLocalTime方法。After you deserialize it, convert it from UTC to local time by calling the ToLocalTime method. 下列範例會使用BinaryFormatter類別來序列化DateTime位於美國的系統上的資料太平洋標準時間時區並將它位於美國的系統上還原序列化中央標準區域。The following example uses the BinaryFormatter class to serialize DateTime data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the U.S. Central Standard zone.

public static void PersistBinary()
{
    SaveDatesBinary();
    RestoreDatesBinary();
}

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

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

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

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

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

    Console.WriteLine("Restored dates...");
}
// When saved on an en-US system, the example displays the following output:
//       Current Time Zone: (UTC-08:00) Pacific Time (US & Canada)
//       The dates on an en-US system:
//       Saturday, June 14, 2014 6:32 AM
//       Thursday, July 10, 2014 11:49 PM
//       Saturday, January 10, 2015 1:16 AM
//       Saturday, December 20, 2014 9:45 PM
//       Monday, June 02, 2014 3:14 PM
//       Saved dates...
//
// When restored on an en-GB system, the example displays the following output:
//       Current Time Zone: (UTC-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 23:45
//       02 June 2014 17:14
//       Restored dates...
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 值可能也會反映在 local 以外的時區與 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.

using System;

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

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

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

        public DateTime DateTime
        {
            get { return (dt); }
            set { dt = value; }
        }
    }
}
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
            If timeZone Is Nothing Then
                tz = TimeZoneInfo.Local
            Else
                tz = timeZone
            End If
        End Sub

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

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

重要

DateWithTimeZone結構用在下面兩個範例中,其序列化和還原序列化的陣列DateWithTimeZone物件。The DateWithTimeZone structure is used in the next two examples, which serialize and deserialize an array of DateWithTimeZone objects. 您可以在檢視這篇文章中的範例整組的來源Visual Basic或是C#從 GitHub 上的 docs 存放庫。You can view the source for the entire set of examples from this article in either Visual Basic or C# from the docs repository on GitHub.

使用DateWithTimeZone結構中,您接著可將日期和時間以及時區資訊。By using the DateWithTimeZone structure, you can then persist date and time along with time zone information. 下列範例會使用BinaryFormatter類別來序列化的陣列DateWithTimeZone物件。The following example uses the BinaryFormatter class to serialize an array of DateWithTimeZone objects.

public static void SaveDateWithTimeZone()
{
    DateWithTimeZone[] dates = { new DateWithTimeZone(new DateTime(2014, 8, 9, 19, 30, 0),
                              TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
                          new DateWithTimeZone(new DateTime(2014, 8, 15, 19, 0, 0),
                              TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")),
                          new DateWithTimeZone(new DateTime(2014, 8, 22, 19, 30, 0),
                              TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")),
                          new DateWithTimeZone(new DateTime(2014, 8, 28, 19, 0, 0),
                              TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")) };
    FileStream fs = new FileStream(@".\Schedule.bin", FileMode.Create);
    BinaryFormatter formatter = new BinaryFormatter();
    try
    {
        formatter.Serialize(fs, dates);
        // Display dates.
        foreach (var date in dates)
        {
            TimeZoneInfo tz = date.TimeZone;
            Console.WriteLine($"{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;
    }

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

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

DateTime vs。TimeSpanDateTime vs. TimeSpan

DateTimeTimeSpan實值型別不同,DateTime代表時間的瞬間而TimeSpan代表時間間隔。The DateTime and TimeSpan value types differ in that a DateTime represents an instant in time whereas a TimeSpan represents a time interval. 您也可以減去一個執行個體DateTime從另一個取得TimeSpan物件,表示它們之間的時間間隔。You can subtract one instance of DateTime from another to obtain a TimeSpan object that represents the time interval between them. 或者,您可以新增正TimeSpan目前DateTime若要取得DateTime表示未來的日期值。Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date.

您可以加入或減去的時間間隔DateTime物件。You can add or subtract a time interval from a DateTime object. 時間間隔可以是負數或正數,並以刻度為單位,例如為單位來表示秒,或做為TimeSpan物件。Time intervals can be negative or positive, and they can be expressed in units such as ticks, seconds, or as a TimeSpan object.

在容許範圍內的相等比較Comparing for equality within tolerance

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

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

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

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

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

    Return Math.Abs(delta) < windowInSeconds
End Function

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

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

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

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

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

COM interop 的考量COM interop considerations

ADateTime傳送到 COM 應用程式,然後傳送回到受管理的應用程式中,值稱為往返。A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. 不過,DateTime只指定時間的值並不會如您所料反覆存取。However, a DateTime value that specifies only a time does not round-trip as you might expect.

如果您反覆存取只有時間,例如下午 3 點,則最後的日期和時間為自 1899 年 12 月 30 日If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. 下午 3:00,而不是 年 1 月 1日日公元 0001at 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 日公元 0001However, the COM system assumes a base date of December 30, 1899 C.E., while the .NET Framework assumes a base date of January, 1, 0001 C.E.

當只有一次從.NET Framework 傳遞至 COM 時,特殊的處理會執行,將時間轉換為 COM 所使用的格式When only a time is passed from the .NET Framework to COM, special processing is performed that converts the time to the format used by COM. 當只有一次從 COM 傳遞至.NET Framework 時,合法的日期和時間,或自 1899 年 12 月 30 日之前會損毀,因為不執行任何特殊處理。When only a time is passed from COM to the .NET Framework, no special processing is performed because that would corrupt legitimate dates and times on or before December 30, 1899. 如果日期從 COM 開始其往返,.NET Framework 和 COM 會保留日期。If a date starts its round-trip from COM, the .NET Framework and COM preserve the date.

.NET Framework 和 COM 的行為表示如果您的應用程式的來回行程DateTime,只指定時間,您的應用程式必須請記得修改,或略過錯誤的日期,從最後DateTime物件。The behavior of the .NET Framework and COM means that if your application round-trips a DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final DateTime object.

建構函式

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

欄位

MaxValue MaxValue MaxValue MaxValue

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

MinValue MinValue MinValue MinValue

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

UnixEpoch UnixEpoch UnixEpoch UnixEpoch

屬性

Date Date Date Date

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

Day Day Day Day

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

DayOfWeek DayOfWeek DayOfWeek DayOfWeek

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

DayOfYear DayOfYear DayOfYear DayOfYear

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

Hour Hour Hour Hour

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

Kind Kind Kind Kind

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

Millisecond Millisecond Millisecond Millisecond

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

Minute Minute Minute Minute

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

Month Month Month Month

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

Now Now Now Now

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

Second Second Second Second

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

Ticks Ticks Ticks Ticks

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

TimeOfDay TimeOfDay TimeOfDay TimeOfDay

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

Today Today Today Today

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

UtcNow UtcNow UtcNow UtcNow

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

Year Year Year Year

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

方法

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

將這個執行個體減去指定的日期和時間。Subtracts the specified date and time from this instance.

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

將這個執行個體減去指定的持續期間。Subtracts the specified duration from this instance.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

運算子

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

明確介面實作

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

適用於

執行緒安全性

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

另請參閱