DateTime 結構

定義

表示時間的瞬間,通常以一天的日期和時間表示。

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

備註

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。 此變更對使用這些日曆的所有應用程式都有影響。 如需詳細資訊,以及判斷您的應用程式是否受到影響,請參閱 在 .NET 的日曆中處理新紀元。 如需在 Windows 系統上測試應用程式以確保其整備時間變更的相關資訊,請參閱 準備您的應用程式以進行日文紀元變更。 如需 .NET 中支援多個紀元的行事曆功能,以及使用支援多個紀元的行事歷時的最佳做法,請參閱 使用紀元

注意

此文章中的某些 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。 選取 [執行] 按鈕以在互動式視窗中執行範例。 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。

Try.NET 內嵌程式碼執行器與 Playground 的當地時區是全球標準時間 (UTC)。 這可能會影響示範 DateTimeDateTimeOffsetTimeZoneInfo 型別與其成員之範例的行為與輸出。

本文包含數個使用 型別的 DateTime 範例:

初始化範例

將物件格式化 DateTime 為字串

將字串剖析為 DateTime 物件

DateTime 解析度

文化特性和行事曆

持續性

本節包含結構許多常見用途 DateTime 的主題:

DateTime 類型代表日期和時間,其值為 00:00:00 (午夜) , 0001 年 1 月 1 日 Anno Domini (Common Era) 到 11:59:59:59 P.M.,9999 年 12 月 31 日 A.D. (C.E.) 西曆。

時間值以 100 奈秒為單位來測量,稱為刻度。 特定日期是日曆中 GregorianCalendar 自 12:00 午夜 12:00 起的刻度數。0001 年 1 月 1 日。 (C.E.) 。 此數位會排除以閏秒新增的刻度。 例如,312413760000000000L 的刻度值代表星期五 0100 12:00:00 午夜的日期。 值 DateTime 一律以明確或預設行事曆的內容表示。

注意

如果您要使用想要轉換成一些其他時間間隔的刻度值,例如分鐘或秒,您應該使用 TimeSpan.TicksPerDayTimeSpan.TicksPerHourTimeSpan.TicksPerMinuteTimeSpan.TicksPerSecondTimeSpan.TicksPerMillisecond 常數來執行轉換。 例如,若要將指定刻度數目所代表的秒數新增至 Second 值的元件 DateTime ,您可以使用 運算式 dateValue.Second + nTicks/Timespan.TicksPerSecond

您可以從 GitHub上的檔存放庫,檢視本文中本文中整個範例集的來源。Visual Basic、 F#C#

注意

使用特定時區中日期和時間值的結構替代 DateTime 方式是 DateTimeOffset 結構。 結構會將 DateTimeOffset 日期和時間資訊儲存在私人 DateTime 欄位中,以及該日期和時間與私人 Int16 欄位中 UTC 不同的分鐘數。 這可讓 DateTimeOffset 值反映特定時區的時間,而 DateTime 值可以明確反映 UTC 和當地時區的時間。 如需使用日期和時間值時使用 DateTime 結構或 DateTimeOffset 結構的討論,請參閱 選擇 DateTime、DateTimeOffset、TimeSpan 和 TimeZoneInfo

初始化 DateTime 物件

您可以透過許多不同的方式,將初始值指派給新的 DateTime 值:

  • 呼叫建構函式,其中指定值的引數,或使用隱含無參數建構函式。
  • DateTime 指派給屬性或方法的傳回值。
  • DateTime從其字串表示剖析值。
  • 使用 Visual Basic 特定的語言功能具現化 DateTime

下列程式碼片段顯示每個程式碼片段的範例。

叫用建構函式

您可以呼叫建構函式的任何多載 DateTime ,以指定日期和時間值的元素, (例如年、月和日,或) 的刻度數目。 下列程式碼會使用 DateTime 指定年、月、日、小時、分鐘和秒的建構函式來建立特定日期。

Dim date1 As New Date(2008, 5, 1, 8, 30, 52)
var date1 = new DateTime(2008, 5, 1, 8, 30, 52);
Console.WriteLine(date1);
let date1 = DateTime(2008, 5, 1, 8, 30, 52)
printfn $"{date1}"

當您想要 DateTime 初始化為其預設值時,您可以叫 DateTime 用結構的隱含無參數建構函式。 (如需實值型別的隱含無參數建構函式的詳細資訊,請參閱 Value Types.) 某些編譯器也支援宣告 DateTime 值,而不需明確指派值。 建立沒有明確初始化的值也會產生預設值。 下列範例說明 DateTime C# 和 Visual Basic 中的隱含無參數建構函式,以及 DateTime Visual Basic 中沒有指派的宣告。

Dim dat1 As DateTime
' The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture))
' The following method call displays True.
Console.WriteLine(dat1.Equals(Date.MinValue))

Dim dat2 As New DateTime()
' The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat2.ToString(System.Globalization.CultureInfo.InvariantCulture))
' The following method call displays True.
Console.WriteLine(dat2.Equals(Date.MinValue))
var dat1 = new DateTime();
// The following method call displays 1/1/0001 12:00:00 AM.
Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture));
// The following method call displays True.
Console.WriteLine(dat1.Equals(DateTime.MinValue));
let dat1 = DateTime()

// The following method call displays 1/1/0001 12:00:00 AM.
printfn $"{dat1.ToString System.Globalization.CultureInfo.InvariantCulture}"

// The following method call displays True.
printfn $"{dat1.Equals DateTime.MinValue}"
指派計算值

您可以將 屬性或方法傳回的日期和時間值指派給 DateTime 物件。 下列範例會將目前的日期和時間、目前的國際標準時間 (UTC) 日期和時間,以及目前的日期指派給三個新的 DateTime 變數。

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;
let date1 = DateTime.Now
let date2 = DateTime.UtcNow
let date3 = DateTime.Today
剖析代表 DateTime 的字串

ParseParseExactTryParseTryParseExact 方法都會將字串轉換成其相等的日期和時間值。 下列範例會使用 ParseParseExact 方法來剖析字串,並將其轉換成 DateTime 值。 第二種格式使用 ISO 8601 標準所支援的表單,以字串格式表示日期和時間。 此標準標記法通常用於傳輸 Web 服務中的日期資訊。

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)
var dateString = "5/1/2008 8:30:52 AM";
DateTime date1 = DateTime.Parse(dateString,
                          System.Globalization.CultureInfo.InvariantCulture);
var iso8601String = "20080501T08:30:52Z";
DateTime dateISO8602 = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ",
                                System.Globalization.CultureInfo.InvariantCulture);
let dateString = "5/1/2008 8:30:52 AM"
let date1 = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture)
let iso8601String = "20080501T08:30:52Z"
let dateISO8602 = DateTime.ParseExact(iso8601String, "yyyyMMddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture)

TryParseTryParseExact 方法會指出字串是否為值的有效表示 DateTime 法,如果為 ,則會執行轉換。

Visual Basic 的語言特定語法

下列 Visual Basic 語句會初始化新的 DateTime 值。

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

DateTime 值及其字串標記法

在內部,所有 DateTime 值都會以刻度數表示, (自 0001 年 1 月 1 日午夜 12:00:00 起經過的 100 奈秒) 間隔數目。 實際 DateTime 值與顯示該值時顯示的方式無關。 值的外觀 DateTime 是格式化作業的結果,可將值轉換成其字串表示。

日期和時間值的外觀取決於文化、國際標準、應用程式需求和個人喜好設定。 結構 DateTime 透過 的多 ToString 載,提供格式化日期和時間值的彈性。 預設 DateTime.ToString() 方法會使用目前文化特性的簡短日期和時間模式,傳回日期和時間值的字串表示。 下列範例使用預設 DateTime.ToString() 方法。 它會使用目前文化特性的簡短日期和時間模式來顯示日期和時間。 en-US 文化特性是執行範例之電腦上的目前文化特性。

var 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
let date1 = DateTime(2008, 3, 1, 7, 0, 0)
printfn $"{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 案例。 您可以使用 方法來指定文化特性, DateTime.ToString(IFormatProvider) 以在特定文化特性中建立簡短的日期和時程表示。 下列範例會使用 方法, DateTime.ToString(IFormatProvider) 使用 fr-FR 文化特性的簡短日期和時間模式來顯示日期和時間。

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

其他應用程式可能需要日期的不同字串表示。 方法 DateTime.ToString(String) 會使用目前文化特性的格式慣例,傳回標準或自訂格式規範所定義的字串標記法。 下列範例會 DateTime.ToString(String) 使用 方法來顯示 en-US 文化特性的完整日期和時間模式,也就是執行範例之電腦上的目前文化特性。

var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F"));
// Displays Saturday, March 01, 2008 7:00:00 AM
let date1 = DateTime(2008, 3, 1, 7, 0, 0)
printfn $"""{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) 。 下列範例會 DateTime.ToString(String, IFormatProvider) 使用 方法來顯示 fr-FR 文化特性的完整日期和時間模式。

var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
Console.WriteLine(date1.ToString("F", new System.Globalization.CultureInfo("fr-FR")));
// Displays samedi 1 mars 2008 07:00:00
let date1 = DateTime(2008, 3, 1, 7, 0, 0)
printfn $"""{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) 載也可以搭配自訂格式字串使用,以指定其他格式。 下列範例示範如何使用通常用於 Web 服務的 ISO 8601 標準格式來格式化字串。 Iso 8601 格式沒有對應的標準格式字串。

var date1 = new DateTime(2008, 3, 1, 7, 0, 0, DateTimeKind.Utc);
Console.WriteLine(date1.ToString("yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture));
// Displays 2008-03-01T07:00:00+00:00
let date1 = DateTime(2008, 3, 1, 7, 0, 0, DateTimeKind.Utc)
printfn $"""{date1.ToString("yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture)}"""
// Displays 2008-03-01T07:00:00+00:00
Dim date1 As DateTime = New DateTime(2008, 3, 1, 7, 0, 0, DateTimeKind.Utc)
Console.WriteLine(date1.ToString("yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture))
' Displays 2008-03-01T07:00:00+00:00

如需格式化 DateTime 值的詳細資訊,請參閱 標準日期和時間格式字串自訂日期和時間格式字串

從字串剖析 DateTime 值

剖析會將日期和時間的字串表示轉換成 DateTime 值。 一般而言,日期和時間字串在應用程式中有兩個不同的用法:

  • 日期和時間會採用各種形式,並反映目前文化特性或特定文化特性的慣例。 例如,應用程式可讓目前文化特性為 en-US 的使用者輸入日期值作為 「12/15/2013」 或 「2013 年 12 月 15 日」。 它可讓目前文化特性為 en-gb 的使用者輸入日期值作為 「15/12/2013」 或 「15 2013 年 12 月 15 日」。

  • 日期和時間是以預先定義的格式表示。 例如,應用程式會將日期序列化為「20130103」,與應用程式執行所在的文化特性無關。 應用程式可能需要以目前文化特性的簡短日期格式輸入日期。

您可以使用 ParseTryParse 方法,將字串從文化特性所使用的其中一個通用日期和時間格式轉換為 DateTime 值。 下列範例示範如何使用 TryParse ,將不同文化特性特定格式 DateTime 的日期字串轉換為值。 它會將目前的文化特性變更為英文 (英國) ,並呼叫 GetDateTimeFormats() 方法來產生日期和時間字串的陣列。 然後,它會將陣列中的每個專案傳遞至 TryParse 方法。 範例的輸出顯示剖析方法能夠成功轉換每個特定文化特性的日期和時間字串。

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

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

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

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

let date1 = DateTime(2013, 6, 1, 12, 32, 30)
let badFormats = ResizeArray<String>()

printfn "%-37s %-19s\n" "Date String" "Date"
for dateString in date1.GetDateTimeFormats() do
    match DateTime.TryParse dateString with
    | true, parsedDate ->
        printfn $"%-37s{dateString} %-19O{parsedDate}\n" 
    | _ ->
        badFormats.Add dateString

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

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

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

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

您可以使用 ParseExactTryParseExact 方法來將必須符合特定格式或格式 DateTime 的字串轉換為值。 您可以將一或多個日期和時間格式字串指定為剖析方法的參數。 下列範例會 TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) 使用 方法來將必須是 「yyyyMMdd」 格式的字串,或 「HHmmss」 格式轉換成 DateTime 值。

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
let formats = [| "yyyyMMdd"; "HHmmss" |]
let dateStrings = 
    [ "20130816"; "20131608"; "  20130816   "
      "115216"; "521116"; "  115216  " ]

for dateString in dateStrings do
    match DateTime.TryParseExact(dateString, formats, null,
                                System.Globalization.DateTimeStyles.AllowWhiteSpaces |||
                                System.Globalization.DateTimeStyles.AdjustToUniversal) with
    | true, parsedDate ->
        printfn $"{dateString} --> {parsedDate:g}"
    | _ ->
        printfn $"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 標準格式。 下列程式碼顯示要使用的正確格式字串:

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

printfn $"{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 方法會擲回例外狀況。 TryParseTryParseExact 方法會傳回值 Boolean ,指出轉換成功或失敗。 您應該在效能很重要的案例中使用 TryParseTryParseExact 方法。 日期和時間字串的剖析作業通常會有較高的失敗率,而且例外狀況處理的成本很高。 如果使用者輸入字串或來自未知的來源,請使用這些方法。

如需剖析日期和時間值的詳細資訊,請參閱 剖析日期和時間字串

DateTime 值

型別中 DateTime 時間值的描述通常會使用國際標準時間 (UTC) 標準來表示。 國際標準時間是 Greenwich Mean Time (GMT) 國際辨識的名稱。 國際標準時間是以零度經度測量的時間,也就是 UTC 源點。 日光節約時間不適用於 UTC。

當地時間相對於特定時區。 時區與時區位移相關聯。 時區位移是從 UTC 源點算起以小時為單位的時區位移。 此外,當地時間會受到日光節約時間的選擇性影響,這會新增或減去時間間隔調整。 當地時間是藉由將時區位移新增至 UTC,並視需要調整日光節約時間來計算。 UTC 來源點的時區位移為零。

UTC 時間適用于計算、比較,以及將日期和時間儲存在檔案中。 當地時間適用于在傳統型應用程式的使用者介面中顯示。 時區感知應用程式 (,例如許多 Web 應用程式) 也需要使用許多其他時區。

Kind如果 物件的 屬性 DateTimeDateTimeKind.Unspecified ,則不會指定表示的時間是當地時間、UTC 時間,還是某些其他時區中的時間。

DateTime 解析

注意

除了對 DateTime 值執行日期和時間算術以測量經過的時間,您也可以使用 Stopwatch 類別。

屬性 Ticks 會以一百萬分之一秒的單位表示日期和時間值。 屬性 Millisecond 會傳回日期和時間值中的千分之一秒。 使用對 屬性的重複呼叫 DateTime.Now 來測量經過的時間取決於系統時鐘。 Windows 7 和 Windows 8 系統上的系統時鐘解析度大約為 15 毫秒。 此解析度會影響小於 100 毫秒的小型時間間隔。

下列範例說明系統時鐘解析上目前日期和時間值的相依性。 在此範例中,外部迴圈會重複 20 次,而內部迴圈則用來延遲外部迴圈。 如果外部迴圈計數器的值是 10,則呼叫 Thread.Sleep 方法會產生五毫秒的延遲。 下列範例顯示內容只會在 呼叫 Thread.Sleep 之後變更所傳 DateTime.Now.Milliseconds 回的毫秒數。

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.
let mutable output = ""
for i = 0 to 20 do
    output <- output + $"{DateTime.Now.Millisecond}\n"
    // Introduce a delay loop.
    for _ = 0 to 1000 do ()

    if i = 10 then
        output <- output + "Thread.Sleep called...\n"
        System.Threading.Thread.Sleep 5

printfn $"{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 結構計算,例如 AddSubtract ,不會修改 結構的值。 相反地,計算會傳回新的 DateTime 結構,其值是計算的結果。

時區之間的轉換作業 (例如 UTC 和當地時間之間,或某個時區與另一個時區之間的轉換作業,) 將日光節約時間納入考慮,但算術和比較運算則不會。

結構 DateTime 本身提供從某個時區轉換為另一個時區的有限支援。 您可以使用 ToLocalTime 方法將 UTC 轉換為當地時間,也可以使用 ToUniversalTime 方法從當地時間轉換為 UTC。 不過,類別中 TimeZoneInfo 提供一組完整的時區轉換方法。 您可以使用這些方法,將任何一個世界時區中的時間轉換為任何其他時區的時間。

只有在物件代表相同時區中的時間時,物件的計算和比較 DateTime 才有意義。 您可以使用 物件來表示 DateTime 值的時區,雖然兩者 TimeZoneInfo 是鬆散結合的。 DateTime物件沒有屬性,會傳回代表該日期和時間值時區的物件。 屬性 Kind 會指出 是否 DateTime 代表 UTC、當地時間或未指定。 在時區感知應用程式中,您必須依賴一些外部機制來判斷物件建立所在的 DateTime 時區。 您可以使用結構來包裝 DateTime 值和 TimeZoneInfo 代表 DateTime 值時區的物件。 如需在計算和值 DateTime 比較中使用 UTC 的詳細資訊,請參閱 使用日期和時間執行算數運算

每個 DateTime 成員都會隱含地使用西曆來執行其作業。 例外狀況是隱含指定行事曆的方法。 其中包括指定行事曆的建構函式,以及具有衍生自 IFormatProvider 的參數的方法,例如 System.Globalization.DateTimeFormatInfo

類型成員的 DateTime 作業會考慮閏年和一個月中的天數等詳細資料。

DateTime 值和行事曆

.NET 類別庫包含一些行事曆類別,這些類別都是衍生自 Calendar 類別。 包括:

重要

日本曆法的紀元是以天皇的統治為基礎,因此有變更是正常的。 例如,2019 年 5 月 1 日之後,JapaneseCalendarJapaneseLunisolarCalendar 中將開始使用「令和」。 此變更對使用這些日曆的所有應用程式都有影響。 如需詳細資訊,以及判斷您的應用程式是否受到影響,請參閱 在 .NET 的日曆中處理新紀元。 如需在 Windows 系統上測試應用程式以確保其整備時間變更的相關資訊,請參閱 準備您的應用程式以進行日文紀元變更。 如需 .NET 中支援多個紀元的行事曆功能,以及使用支援多個紀元的行事歷時的最佳做法,請參閱 使用紀元

每個文化特性都會使用其唯讀 CultureInfo.Calendar 屬性所定義的預設行事曆。 每個文化特性都可能支援其唯讀 CultureInfo.OptionalCalendars 屬性所定義的一或多個行事曆。 特定 CultureInfo 物件目前使用的行事曆是由其 DateTimeFormatInfo.Calendar 屬性所定義。 它必須是陣列中找到 CultureInfo.OptionalCalendars 的其中一個行事曆。

文化特性的目前行事曆用於該文化特性的所有格式設定作業。 例如,泰文文文化的預設行事曆是泰文紀元曆,由 類別表示 ThaiBuddhistCalendarCultureInfo當代表泰文文文化特性的物件用於日期和時間格式設定作業時,預設會使用泰文紀元行事曆。 只有在文化特性的 DateTimeFormatInfo.Calendar 屬性變更時,才會使用西曆,如下列範例所示:

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));
// The example displays the following output:
//       28/5/2559 0:00:00
//       28/5/2016 0:00:00
let thTH = System.Globalization.CultureInfo "th-TH"
let value = DateTime(2016, 5, 28)

printfn $"{value.ToString thTH}"

thTH.DateTimeFormat.Calendar <- System.Globalization.GregorianCalendar()

printfn $"{value.ToString thTH}"

// The example displays the following output:
//       28/5/2559 0:00:00
//       28/5/2016 0:00:00
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

文化特性的目前行事曆也會用於該文化特性的所有剖析作業,如下列範例所示。

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));
// The example displays the following output:
//       28/5/2559 0:00:00
//       28/5/2016 0:00:00
let thTH = System.Globalization.CultureInfo "th-TH"
let value = DateTime.Parse("28/05/2559", thTH)
printfn $"{value.ToString thTH}"

thTH.DateTimeFormat.Calendar <- System.Globalization.GregorianCalendar()
printfn $"{value.ToString thTH}"

// The example displays the following output:
//       28/5/2559 0:00:00
//       28/5/2016 0:00:00
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

您可以藉由呼叫包含 calendar 參數的 DateTime 建構函式,並將代表該行事曆的 物件傳遞 Calendar 至代表該行事曆的DateTime建構函式,以使用日期與時間元素 (年、月和日) 來具現 DateTime 化值。 下列範例會使用行事曆中的 ThaiBuddhistCalendar 日期和時間元素。

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}");
// The example displays the following output:
//       Thai Buddhist Era Date:  28/5/2559
//       Gregorian Date:     28/05/2016
let thTH = System.Globalization.CultureInfo "th-TH"
let dat = DateTime(2559, 5, 28, thTH.DateTimeFormat.Calendar)

printfn $"""Thai Buddhist era date: {dat.ToString("d", thTH)}"""
printfn $"Gregorian date:   {dat:d}"

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

DateTime 不包含 calendar 參數的建構函式會假設日期和時間元素是以西曆中的單位表示。

所有其他 DateTime 屬性和方法都會使用西曆。 例如, DateTime.Year 屬性會傳回西曆中的年份,而 DateTime.IsLeapYear(Int32) 方法會 year 假設 參數是西曆中的年份。 使用西曆的每個 DateTime 成員都有使用特定行事曆之類別的 Calendar 對應成員。 例如,方法會 Calendar.GetYear 傳回特定行事曆中的年份,而 Calendar.IsLeapYear 方法會將 year 參數解譯為特定行事曆中的年份數位。 下列範例會 DateTime 同時使用 和 類別的 ThaiBuddhistCalendar 對應成員。

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)}");
// 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
let thTH = System.Globalization.CultureInfo "th-TH"
let cal = thTH.DateTimeFormat.Calendar
let dat = DateTime(2559, 5, 28, cal)
printfn "Using the Thai Buddhist Era calendar:"
printfn $"""Date: {dat.ToString("d", thTH)}"""
printfn $"Year: {cal.GetYear dat}"
printfn $"Leap year: {cal.IsLeapYear(cal.GetYear dat)}\n"

printfn "Using the Gregorian calendar:"
printfn $"Date: {dat:d}"
printfn $"Year: {dat.Year}"
printfn $"Leap year: {DateTime.IsLeapYear dat.Year}"

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

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

結構 DateTime 包含 DayOfWeek 屬性,這個屬性會傳回西曆中的星期幾。 它不包含可讓您擷取年份周數的成員。 若要擷取年份的周,請呼叫個別行事曆的 Calendar.GetWeekOfYear 方法。 下列範例提供說明。

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)}");
// 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
let thTH = System.Globalization.CultureInfo "th-TH"
let thCalendar = thTH.DateTimeFormat.Calendar
let dat = DateTime(1395, 8, 18, thCalendar)
printfn "Using the Thai Buddhist Era calendar:"
printfn $"""Date: {dat.ToString("d", thTH)}"""
printfn $"Day of Week: {thCalendar.GetDayOfWeek dat}"
printfn $"Week of year: {thCalendar.GetWeekOfYear(dat, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}\n"

let greg = System.Globalization.GregorianCalendar()
printfn "Using the Gregorian calendar:"
printfn $"Date: {dat:d}"
printfn $"Day of Week: {dat.DayOfWeek}"
printfn $"Week of year: {greg.GetWeekOfYear(dat, System.Globalization.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
Dim thTH As New CultureInfo("th-TH")
Dim thCalendar As Calendar = thTH.DateTimeFormat.Calendar
Dim dat As New DateTime(1395, 8, 18, thCalendar)
Console.WriteLine("Using the Thai Buddhist Era calendar:")
Console.WriteLine($"Date: {dat.ToString("d", thTH)}")
Console.WriteLine($"Day of Week: {thCalendar.GetDayOfWeek(dat)}")
Console.WriteLine($"Week of year: {thCalendar.GetWeekOfYear(dat, CalendarWeekRule.FirstDay, DayOfWeek.Sunday)}")
Console.WriteLine()

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

如需日期和行事曆的詳細資訊,請參閱 使用行事曆

保存 DateTime 值

您可以透過下列方式保存 DateTime 值:

您必須確定還原 DateTime 值的常式不會遺失資料或擲回例外狀況,不論您選擇的技術為何。 DateTime 值應該往返。 也就是說,原始值和還原的值應該相同。 如果原始 DateTime 值代表單一時間點,它應該會在還原時識別相同的時間點。

將值保存為字串

若要成功還原 DateTime 保存為字串的值,請遵循下列規則:

將值保存 DateTime 為字串時,最常見的錯誤是依賴預設或目前文化特性的格式慣例。 儲存和還原字串時,如果目前的文化特性不同,就會發生問題。 下列範例說明這些問題。 它會使用目前文化特性的格式設定慣例來儲存五個日期,在此案例中為英文 (美國) 。 它會使用不同文化特性的格式設定慣例來還原日期,在此案例中為英文 (英國) 。 因為兩個文化特性的格式慣例不同,所以無法還原兩個日期,其餘的三個日期會不正確解譯。 此外,如果原始日期和時間值代表單一時間點,還原的時間會不正確,因為時區資訊遺失。

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 ? "|" : "");
    }
    var 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...
let saveLocalDatesAsString () =
    let dates = 
        [ DateTime(2014, 6, 14, 6, 32, 0)
          DateTime(2014, 7, 10, 23, 49, 0)
          DateTime(2015, 1, 10, 1, 16, 0)
          DateTime(2014, 12, 20, 21, 45, 0)
          DateTime(2014, 6, 2, 15, 14, 0) ]

    printfn $"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"
    printfn $"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"

    let output =
        [ for date in dates do
            printfn $"{date}"
            string date ]
        |> String.concat "|"

    use sw = new StreamWriter(filenameTxt)
    sw.Write output
    printfn "Saved dates..."

let restoreLocalDatesFromString () =
    TimeZoneInfo.ClearCachedData()
    printfn $"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-GB"

    use sr = new StreamReader(filenameTxt)
    let inputValues = 
        sr.ReadToEnd().Split('|', StringSplitOptions.RemoveEmptyEntries)

    printfn $"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"

    for inputValue in inputValues do
        match DateTime.TryParse inputValue with
        | true, dateValue ->
            printfn $"'{inputValue}' --> {dateValue:f}"
        | _ ->
            printfn $"Cannot parse '{inputValue}'"

    printfn "Restored dates..."

let persistAsLocalStrings () =
    saveLocalDatesAsString ()
    restoreLocalDatesFromString ()

// 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 值,請遵循下列步驟:

  1. 如果值代表單一時間點,請呼叫 ToUniversalTime 方法,將它們從當地時間轉換成 UTC。
  2. 呼叫 或 String.Format(IFormatProvider, String, Object[]) 多載,將日期轉換為其字串表示 ToString(String, IFormatProvider) 。 藉由將 指定 CultureInfo.InvariantCultureprovider 引數,以使用不因文化特性而異的格式慣例。 使用 「O」 或 「R」 標準格式字串來指定值應該來回。

若要還原保存 DateTime 的值而不遺失資料,請遵循下列步驟:

  1. 呼叫 ParseExactTryParseExact 多載來剖析資料。 指定 CultureInfo.InvariantCultureprovider 引數,並使用您在轉換期間用於 format 引數的相同標準格式字串。 在 DateTimeStyles.RoundtripKind 引數中包含 styles 值。
  2. DateTime如果值代表單一時間點,請呼叫 ToLocalTime 方法,將剖析日期從 UTC 轉換為當地時間。

下列範例會使用非變異文化特性和 「O」 標準格式字串,以確保儲存和還原的值代表 DateTime 相同的時間點,而不論來源和目標系統的系統、文化特性或時區為何。

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 ? "|" : "");
    }
    var 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...
let saveDatesAsInvariantStrings () =
    let dates = 
        [ DateTime(2014, 6, 14, 6, 32, 0)
          DateTime(2014, 7, 10, 23, 49, 0)
          DateTime(2015, 1, 10, 1, 16, 0)
          DateTime(2014, 12, 20, 21, 45, 0)
          DateTime(2014, 6, 2, 15, 14, 0) ]

    printfn $"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"
    printfn $"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"

    let output =
        [ for date in dates do
            printfn $"{date:f}"
            date.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture) ]
        |> String.concat "|"

    use sw = new StreamWriter(filenameTxt)
    sw.Write output
    printfn "Saved dates..."

let restoreDatesAsInvariantStrings () =
    TimeZoneInfo.ClearCachedData()
    printfn $"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-GB"
    
    use sr = new StreamReader(filenameTxt)
    let inputValues = 
        sr.ReadToEnd().Split('|', StringSplitOptions.RemoveEmptyEntries)

    printfn $"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"

    for inputValue in inputValues do
        match DateTime.TryParseExact(inputValue, "O", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind) with
        | true, dateValue ->
            printfn $"'{inputValue}' --> {dateValue.ToLocalTime():f}"
        | _ ->
            printfn $"Cannot parse '{inputValue}'"

    printfn "Restored dates..."

let persistAsInvariantStrings () =
    saveDatesAsInvariantStrings ()
    restoreDatesAsInvariantStrings ()

// 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...
將值保存為整數

您可以將日期和時間保存為 Int64 代表一些刻度的值。 在此情況下,您不需要考慮保存 DateTime 值並還原的系統文化特性。

若要將 DateTime 值保存為整數:

若要還原 DateTime 已保存為整數的值:

  1. 將 值傳遞至 DateTime(Int64) 建構函式, Int64 以具現化新的 DateTime 物件。
  2. DateTime如果值代表單一時間點,請呼叫 ToLocalTime 方法,將它從 UTC 轉換為當地時間。

下列範例會將值陣列 DateTime 保存為美國太平洋時區系統中的整數。 它會在 UTC 區域中的系統上還原它。 包含整數的檔案包含值 Int32 ,指出緊接在它之後的值總數 Int64

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:");
    var 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;
    }
    var fs = new FileStream(filenameInts, FileMode.Create);
    var 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...
let saveDatesAsInts () =
    let dates = 
        [ DateTime(2014, 6, 14, 6, 32, 0)
          DateTime(2014, 7, 10, 23, 49, 0)
          DateTime(2015, 1, 10, 1, 16, 0)
          DateTime(2014, 12, 20, 21, 45, 0)
          DateTime(2014, 6, 2, 15, 14, 0) ]

    printfn $"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"
    printfn $"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"
    let ticks =
        [| for date in dates do
            printfn $"{date:f}"
            date.ToUniversalTime().Ticks |]
    use fs = new FileStream(filenameInts, FileMode.Create)
    use bw = new BinaryWriter(fs)
    bw.Write ticks.Length

    for tick in ticks do
        bw.Write tick

    printfn "Saved dates..."

let restoreDatesAsInts () =
    TimeZoneInfo.ClearCachedData()
    printfn $"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-GB"
    use fs = new FileStream(filenameInts, FileMode.Open)
    use br = new BinaryReader(fs)

    try
        let items = br.ReadInt32()
        let dates =
            [| for _ in 0..items do
                let ticks = br.ReadInt64()
                DateTime(ticks).ToLocalTime() |]

        printfn $"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"
        for value in dates do
            printfn $"{value:f}"
    with 
    | :? EndOfStreamException ->
        printfn "File corruption detected. Unable to restore data..."
    | :? IOException ->
        printfn "Unspecified I/O error. Unable to restore data..."
    // Thrown during array initialization.
    | :? OutOfMemoryException ->
        printfn"File corruption detected. Unable to restore data..."

    printfn "Restored dates..."

let persistAsIntegers () =
    saveDatesAsInts ()
    restoreDatesAsInts ()

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

序列化 DateTime 值

您可以透過序列化將值保存到 DateTime 資料流程或檔案,然後透過還原序列化加以還原還原。 DateTime 資料會以某些指定的物件格式序列化。 還原序列化物件時,會還原這些物件。 格式器或序列化程式,例如 JsonSerializerXmlSerializer ,會處理序列化和還原序列化的程式。 如需有關序列化和 .NET 所支援序列化類型的詳細資訊,請參閱 序列化

下列範例會使用 類別 XmlSerializer 來序列化和還原序列化 DateTime 值。 這些值代表二十一年中的所有閏年天數。 如果範例是在目前文化特性為英文 (英國) 的系統上執行,則輸出代表結果。 因為您已還原序列化 DateTime 物件本身,所以程式碼不需要處理日期和時間格式的文化差異。

public static void PersistAsXML()
{
    // Serialize the data.
    var 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();

    var 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 (var 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;
    if (deserializedDates is not null)
    {
        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
let persistAsXML () =
    // Serialize the data.
    let leapYears =
        [| for year in 2000..4..2100 do
            if DateTime.IsLeapYear year then
                DateTime(year, 2, 29) |]

    let serializer = XmlSerializer(leapYears.GetType())
    use sw = new StreamWriter(filenameXml)

    try
        serializer.Serialize(sw, leapYears)
    with :? InvalidOperationException as e ->
        printfn $"{e.InnerException.Message}"

    // Deserialize the data.
    use fs = new FileStream(filenameXml, FileMode.Open)
        
    let deserializedDates = serializer.Deserialize fs :?> DateTime []

    // Display the dates.
    printfn $"Leap year days from 2000-2100 on an {Thread.CurrentThread.CurrentCulture.Name} system:"
    
    let mutable nItems = 0
    for dat in deserializedDates do
        printf $"   {dat:d}     "
        nItems <- nItems + 1
        if nItems % 5 = 0 then
            printfn ""

// 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

上述範例不包含時間資訊。 DateTime如果值代表某個時間點,並以當地時程表示,請先從當地時間轉換為 UTC,再呼叫 ToUniversalTime 方法將其序列化。 還原序列化之後,請呼叫 ToLocalTime 方法,將它從 UTC 轉換為當地時間。

DateTime 與 TimeSpan

DateTimeTimeSpan 實值型別的差異在於 , DateTime 代表時間的瞬間,而 TimeSpan 表示時間間隔。 您可以從另一個 實例中減去一個 實例 DateTime ,以取得 TimeSpan 代表它們之間時間間隔的 物件。 或者,您可以將正 TimeSpan 值加入至目前的 DateTime ,以取得 DateTime 代表未來日期的值。

您可以從 物件加入或減去時間間隔 DateTime 。 時間間隔可以是負數或正數,並以刻度、秒或 TimeSpan 物件等單位表示。

比較容錯內的相等

值的相等比較是確切的 DateTime 。 這表示兩個值必須以相同數目的刻度表示,才能視為相等。 對於許多應用程式而言,這個精確度通常不必要或甚至不正確。 通常,您想要測試物件是否 DateTime大致相等

下列範例示範如何比較大致相等 DateTime 的值。 當宣告相等時,它會接受小邊界的差異。

public static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds)
{
    long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds % frequencyInSeconds;
    delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta;
    return Math.Abs(delta) < windowInSeconds;
}

public static void TestRoughlyEquals()
{
    int window = 10;
    int freq = 60 * 60 * 2; // 2 hours;

    DateTime d1 = DateTime.Now;

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

    DateTime d6 = (d1.AddHours(2)).AddSeconds(2 * window);
    DateTime d7 = (d1.AddHours(2)).AddSeconds(-2 * window);
    DateTime d8 = (d1.AddHours(2)).AddSeconds(window / 2);
    DateTime d9 = (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)}");
}
// 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
let roughlyEquals (time: DateTime) (timeWithWindow: DateTime) windowInSeconds frequencyInSeconds =
    let delta = 
        int64 (timeWithWindow - time).TotalSeconds % frequencyInSeconds
    
    let delta = if delta > windowInSeconds then frequencyInSeconds - delta else delta
    abs delta < windowInSeconds

let testRoughlyEquals () =
    let window = 10
    let window' = 10.
    let freq = 60 * 60 * 2 // 2 hours

    let d1 = DateTime.Now

    let d2 = d1.AddSeconds(2. * window')
    let d3 = d1.AddSeconds(-2. * window')
    let d4 = d1.AddSeconds(window' / 2.)
    let d5 = d1.AddSeconds(-window' / 2.)

    let d6 = (d1.AddHours 2).AddSeconds(2. * window')
    let d7 = (d1.AddHours 2).AddSeconds(-2. * window')
    let d8 = (d1.AddHours 2).AddSeconds(window' / 2.)
    let d9 = (d1.AddHours 2).AddSeconds(-window' / 2.)

    printfn $"d1 ({d1}) ~= d1 ({d1}): {roughlyEquals d1 d1 window freq}"
    printfn $"d1 ({d1}) ~= d2 ({d2}): {roughlyEquals d1 d2 window freq}"
    printfn $"d1 ({d1}) ~= d3 ({d3}): {roughlyEquals d1 d3 window freq}"
    printfn $"d1 ({d1}) ~= d4 ({d4}): {roughlyEquals d1 d4 window freq}"
    printfn $"d1 ({d1}) ~= d5 ({d5}): {roughlyEquals d1 d5 window freq}"

    printfn $"d1 ({d1}) ~= d6 ({d6}): {roughlyEquals d1 d6 window freq}"
    printfn $"d1 ({d1}) ~= d7 ({d7}): {roughlyEquals d1 d7 window freq}"
    printfn $"d1 ({d1}) ~= d8 ({d8}): {roughlyEquals d1 d8 window freq}"
    printfn $"d1 ({d1}) ~= d9 ({d9}): {roughlyEquals d1 d9 window freq}"

// 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
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 考慮

DateTime傳送至 COM 應用程式的值,接著會轉送回受控應用程式,稱為來回行程。 不過, DateTime 僅指定時間的值不會如預期般來回。

如果您只來回一個時間,例如下午 3 點,最終日期和時間是 1899 年 12 月 30 日 C.E.下午 3:00,而不是下午 1:0001 C.E. 下午 3:00。.NET Framework和 COM 假設只有指定時間時的預設日期。 不過,COM 系統假設基底日期為 1899 年 12 月 30 日 C.E.,而.NET Framework假設為 0001 年 1 月 1 日 C.E 的基底日期。

當只有時間從 .NET Framework 傳遞至 COM 時,會執行特殊處理,以將時間轉換為 COM 所使用的格式。 當只有時間從 COM 傳遞至.NET Framework時,不會執行任何特殊處理,因為這會在 1899 年 12 月 30 日或之前損毀合法日期和時間。 如果日期從 COM 開始往返,.NET Framework和 COM 會保留日期。

.NET Framework和 COM 的行為表示,如果您的應用程式往返 DateTime 僅指定時間,您的應用程式必須記得修改或忽略最後 DateTime 一個物件的錯誤日期。

建構函式

DateTime(DateOnly, TimeOnly)

將 結構的新實例 DateTime 初始化為指定的 DateOnlyTimeOnly 。 新的實例將具有 種類 Unspecified

DateTime(DateOnly, TimeOnly, DateTimeKind)

將 結構的新實例 DateTime 初始化為指定的 DateOnlyTimeOnly 並遵守指定的 DateTimeKind

DateTime(Int32, Int32, Int32)

DateTime 結構的新執行個體初始化為指定的年、月和日。

DateTime(Int32, Int32, Int32, Calendar)

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月和日。

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

DateTime 結構的新執行個體初始化為指定的年、月、日、時、分和秒。

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分和秒。

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

DateTime 結構的新執行個體初始化為指定年、月、日、時、分、秒以及國際標準時間 (UTC) 或本地時間。

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

DateTime 結構的新執行個體初始化為指定的年、月、日、時、分、秒和毫秒。

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒和毫秒。

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。

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

DateTime 結構的新執行個體初始化為指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。

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

DateTime 結構的新執行個體初始化為指定行事曆的指定年、月、日、時、分、秒、毫秒以及國際標準時間 (UTC) 或本地時間。

DateTime(Int64)

DateTime 結構的新執行個體初始化為刻度的指定數目。

DateTime(Int64, DateTimeKind)

DateTime 結構的新執行個體初始化為指定的刻度數以及國際標準時間 (UTC) 或本地時間。

欄位

MaxValue

代表 DateTime 最大的可能值。 此欄位為唯讀。

MinValue

代表 DateTime 最小的可能值。 此欄位為唯讀。

UnixEpoch

這個常數的值相當於西曆中的國際標準時間 00:00:00.0000000,1970 年 1 月 1 日。 UnixEpoch 定義 UNIX 時間等於 0 的時間點。

屬性

Date

取得這個執行個體的日期部分。

Day

取得由這個執行個體表示的月份天數。

DayOfWeek

取得由這個執行個體表示的一週天數。

DayOfYear

取得由這個執行個體表示的一年天數。

Hour

取得這個執行個體所表示日期的小時元件。

Kind

取得值,指出這個執行個體表示的時間是根據本地時間、國際標準時間 (UTC),或兩者皆非。

Microsecond

微秒元件,以介於 0 到 999 之間的值表示。

Millisecond

取得這個執行個體所表示日期的毫秒元件。

Minute

取得這個執行個體所表示日期的分鐘元件。

Month

取得這個執行個體所表示日期的月份元件。

Nanosecond

nanoseconds 元件,以介於 0 到 900 (之間的值表示,以 100 奈秒為單位遞增) 。

Now

取得 DateTime 物件,此物件會設定為這部電腦上目前的日期和時間,以本地時間表示。

Second

取得這個執行個體所表示日期的秒數元件。

Ticks

取得表示這個執行個體日期和時間的刻度數目。

TimeOfDay

取得這個執行個體的一天時間。

Today

取得目前的日期。

UtcNow

取得 DateTime 物件,此物件會設定為這部電腦上目前的日期和時間,以國際標準時間 (UTC) 表示。

Year

取得這個執行個體所表示日期的年份元件。

方法

Add(TimeSpan)

傳回新的 DateTime,將這個執行個體的值加上指定之 TimeSpan 的值。

AddDays(Double)

傳回新的 DateTime,將這個執行個體的值加上指定的天數。

AddHours(Double)

傳回新的 DateTime,將這個執行個體的值加上指定的時數。

AddMicroseconds(Double)

傳回新的 DateTime ,將指定的微秒數新增至這個實例的值。

AddMilliseconds(Double)

傳回新的 DateTime,將這個執行個體的值加上指定的毫秒數。

AddMinutes(Double)

傳回新的 DateTime,將這個執行個體的值加上指定的分鐘數。

AddMonths(Int32)

傳回新的 DateTime,將這個執行個體的值加上指定的月數。

AddSeconds(Double)

傳回新的 DateTime,將這個執行個體的值加上指定的秒數。

AddTicks(Int64)

傳回新的 DateTime,將這個執行個體的值加上指定的刻度數。

AddYears(Int32)

傳回新的 DateTime,將這個執行個體的值加上指定的年數。

Compare(DateTime, DateTime)

比較 DateTime 的兩個執行個體,並傳回整數,這個整數表示第一個執行個體早於、同於或晚於第二個執行個體。

CompareTo(DateTime)

比較這個執行個體的值與指定的 DateTime 值,並且傳回一個整數,指出這個執行個體是早於、同於或晚於指定的 DateTime 值。

CompareTo(Object)

比較這個執行個體的值與含有指定之 DateTime 值的指定物件,並且傳回一個整數,指出這個執行個體是早於、同於或晚於指定的 DateTime 值。

DaysInMonth(Int32, Int32)

傳回所指定年份中指定月份的天數。

Deconstruct(DateOnly, TimeOnly)

將這個 DateTime 實例解構為 DateOnlyTimeOnly

Deconstruct(Int32, Int32, Int32)

將這個 DateOnly 實例解構為 YearMonthDay

Equals(DateTime)

傳回值,該值指出這個執行個體的值是否等於指定之 DateTime 執行個體的值。

Equals(DateTime, DateTime)

傳回值,指出兩 DateTime 個實例是否有相同的日期和時間值。

Equals(Object)

傳回值,該值表示這個執行個體是否和指定的物件相等。

FromBinary(Int64)

還原序列化 64 位元的二進位值,並重新建立原始的序列化 DateTime 物件。

FromFileTime(Int64)

將指定的 Windows 檔案時間轉換成相等的本地時間。

FromFileTimeUtc(Int64)

將指定的 Windows 檔案時間轉換成相等的 UTC 時間。

FromOADate(Double)

傳回等於指定 OLE Automation 日期的 DateTime

GetDateTimeFormats()

將這個執行個體的值轉換為標準日期和時間格式規範所支援的所有字串表示。

GetDateTimeFormats(Char)

將這個執行個體的值轉換為指定的標準日期和時間格式規範所支援的所有字串表示。

GetDateTimeFormats(Char, IFormatProvider)

將這個執行個體的值轉換為指定的標準日期和時間格式規範和特定文化特性格式資訊所支援的所有字串表示。

GetDateTimeFormats(IFormatProvider)

將這個執行個體的值轉換為標準日期和時間格式規範和指定的特定文化特性格式資訊所支援的所有字串表示。

GetHashCode()

傳回這個執行個體的雜湊碼。

GetTypeCode()

傳回實值類型 TypeCodeDateTime

IsDaylightSavingTime()

指出這個 DateTime 執行個體是否在目前時區的日光節約時間範圍內。

IsLeapYear(Int32)

傳回指定年份是否為閏年的指示。

Parse(ReadOnlySpan<Char>, IFormatProvider)

將字元範圍剖析為值。

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

使用文化特定格式資訊及格式化樣式,將包含日期與時間字串表示的記憶體範圍轉換成相等 DateTime

Parse(String)

使用目前文化特性的慣例,將日期和時間的字串表示轉換為相 DateTime 等的。

Parse(String, IFormatProvider)

使用特定文化特性格式資訊,將日期和時間的字串表示轉換為其相等的 DateTime

Parse(String, IFormatProvider, DateTimeStyles)

使用特定文化特性格式資訊及格式樣式,將日期和時間的字串表示轉換為其相等的 DateTime

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

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTime。 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。

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

使用指定格式、特定文化特性格式資訊以及樣式的陣列,以將日期和時間的指定範圍表示轉換為與其相等的 DateTime。 字串表示的格式必須至少完全符合其中一個指定的格式,否則會擲回例外狀況。

ParseExact(String, String, IFormatProvider)

使用指定的格式以及特定文化特性的格式資訊,將日期和時間的指定字串表示,轉換為其相等的 DateTime。 字串表示的格式必須完全符合指定的格式。

ParseExact(String, String, IFormatProvider, DateTimeStyles)

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTime。 字串表示的格式必須完全符合指定的格式,否則會擲回例外狀況。

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTime。 字串表示的格式必須至少完全符合其中一個指定的格式,否則會擲回例外狀況。

SpecifyKind(DateTime, DateTimeKind)

建立新的 DateTime 物件,此物件的刻度數與指定的 DateTime 相同,但依指定的 DateTimeKind 值所示,指定為本地時間、國際標準時間 (Coordinated Universal Time,UTC),或兩者都不是。

Subtract(DateTime)

傳回會將指定日期和時間從此執行個體的值減去的新 TimeSpan

Subtract(TimeSpan)

傳回會將指定期間從此執行個體的值減去的新 DateTime

ToBinary()

將目前的 DateTime 物件序列化成 64 位元的二進位值,之後可以用這個值來重新建立 DateTime 物件。

ToFileTime()

將目前 DateTime 物件的值轉換成 Windows 檔案時間。

ToFileTimeUtc()

將目前 DateTime 物件的值轉換成 Windows 檔案時間。

ToLocalTime()

將目前 DateTime 物件的值轉換成本地時間。

ToLongDateString()

將目前 DateTime 物件的值轉換為其相等的完整日期 (Long Date) 字串表示。

ToLongTimeString()

將目前 DateTime 物件的值轉換為其相等的完整時間 (Long Time) 字串表示。

ToOADate()

將這個執行個體的值轉換為相等的 OLE Automation 日期。

ToShortDateString()

將目前 DateTime 物件的值轉換為其相等的簡短日期 (Short Date) 字串表示。

ToShortTimeString()

將目前 DateTime 物件的值轉換為其相等的簡短時間 (Short Time) 字串表示。

ToString()

使用目前文化特性的格式化慣例,將目前 DateTime 物件的值轉換為其相等的字串表示。

ToString(IFormatProvider)

使用指定的特定文化特性格式資訊,將目前 DateTime 物件的值轉換為其相等的字串表示。

ToString(String)

使用指定的格式和目前文化特性的格式化慣例,將目前 DateTime 物件的值轉換為其相等的字串表示。

ToString(String, IFormatProvider)

使用指定的格式和特定文化特性的格式資訊,將目前 DateTime 物件的值,轉換為其相等的字串表示。

ToUniversalTime()

將目前 DateTime 物件的值轉換成國際標準時間 (UTC)。

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

嘗試將目前實例的值格式化為 UTF-8 到提供的位元組範圍。

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

嘗試將目前日期時間執行個體的值格式化為所提供字元範圍。

TryParse(ReadOnlySpan<Char>, DateTime)

將日期和時間的指定字元範圍轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。

TryParse(ReadOnlySpan<Char>, IFormatProvider, DateTime)

嘗試將字元範圍剖析成值。

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

使用指定的特定文化特性格式資訊和格式樣式,以將日期和時間的範圍表示轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。

TryParse(String, DateTime)

將日期和時間的指定字串表示,轉換為其相等的 DateTime,並傳回一個值表示轉換是否成功。

TryParse(String, IFormatProvider, DateTime)

嘗試將字串剖析成值。

TryParse(String, IFormatProvider, DateTimeStyles, DateTime)

使用指定的特定文化特性格式資訊和格式樣式,將日期和時間的指定字串表示轉換為其相等的 DateTime,並傳回值,這個值表示轉換是否成功。

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

使用指定的格式、特定文化特性格式資訊以及樣式,以將日期和時間的指定範圍表示轉換為與其相等的 DateTime。 字串表示的格式必須完全符合指定的格式。 此方法會傳回值,這個值表示轉換是否成功。

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

將日期和時間的指定字元範圍轉換為與其相等的 DateTime,並傳回一個值表示轉換是否成功。

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

使用指定的格式、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTime。 字串表示的格式必須完全符合指定的格式。 此方法會傳回值,這個值表示轉換是否成功。

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

使用指定的格式陣列、特定文化特性格式資訊以及樣式,將日期和時間的指定字串表示,轉換為其相等的 DateTime。 字串表示的格式必須至少完全符合其中一個指定格式。 此方法會傳回值,這個值表示轉換是否成功。

運算子

Addition(DateTime, TimeSpan)

將指定的日期和時間加上指定的時間間隔,產生新的日期和時間。

Equality(DateTime, DateTime)

判斷 DateTime 的兩個指定執行個體是否相等。

GreaterThan(DateTime, DateTime)

判斷某個指定的 DateTime 是否晚於另一個指定的 DateTime

GreaterThanOrEqual(DateTime, DateTime)

判斷某個指定之 DateTime 表示的是同於還是晚於另一個指定之 DateTime 的日期和時間。

Inequality(DateTime, DateTime)

判斷 DateTime 的兩個指定執行個體是否不相等。

LessThan(DateTime, DateTime)

判斷某個指定的 DateTime 是否早於另一個指定的 DateTime

LessThanOrEqual(DateTime, DateTime)

判斷某個指定之 DateTime 表示的是同於還是早於另一個指定之 DateTime 的日期和時間。

Subtraction(DateTime, DateTime)

將另一個指定的日期和時間減去指定的日期和時間,並傳回時間間隔。

Subtraction(DateTime, TimeSpan)

將指定的日期和時間減去指定的時間間隔,並傳回新的日期和時間。

明確介面實作

IComparable.CompareTo(Object)

將目前的執行個體與相同類型的另一個物件相比較,並傳回整數,這個整數表示目前的執行個體在排序次序中,位於另一個物件之前、之後或相同位置。

IConvertible.GetTypeCode()

傳回這個執行個體的 TypeCode

IConvertible.ToBoolean(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToByte(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToChar(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToDateTime(IFormatProvider)

傳回目前的 DateTime物件。

IConvertible.ToDecimal(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToDouble(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToInt16(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToInt32(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToInt64(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToSByte(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToSingle(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToType(Type, IFormatProvider)

將目前的 DateTime 物件轉換為指定類型的物件。

IConvertible.ToUInt16(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToUInt32(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToUInt64(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用序列化目前 SerializationInfo 物件所需的資料,填入 DateTime 物件。

適用於

執行緒安全性

此類型的所有成員都是安全線程。 看似修改實例狀態的成員,實際上會傳回以新值初始化的新實例。 如同任何其他類型,讀取和寫入包含此類型實例的共用變數必須受到鎖定保護,以確保執行緒安全。

另請參閱