DateTime.Parse 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將日期和時間的字串表示轉換為其相等的 DateTime。
多載
Parse(String) |
使用目前文化特性的慣例,將日期和時間的字串表示轉換為其相等的 DateTime。 |
Parse(ReadOnlySpan<Char>, IFormatProvider) |
將字元範圍剖析為值。 |
Parse(String, IFormatProvider) |
使用特定文化特性格式資訊,將日期和時間的字串表示轉換成其相等 DateTime。 |
Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) |
使用特定文化特性格式資訊和格式樣式,將包含日期和時間字串表示的記憶體範圍轉換為其相等的 DateTime。 |
Parse(String, IFormatProvider, DateTimeStyles) |
使用特定文化特性格式資訊和格式樣式,將日期和時間的字串表示轉換為其相等的 DateTime。 |
範例
許多呼叫
注意
本文中的一些 C# 範例會在 Try.NET 內嵌程式代碼執行器和遊樂場中執行。 選取 [[執行],以在互動式視窗中執行範例。 執行程式代碼之後,您可以再次選取 [執行] [執行] 來修改並執行修改的程序代碼。 修改過的程式代碼會在互動式視窗中執行,或者,如果編譯失敗,互動式視窗會顯示所有 C# 編譯程式錯誤訊息。
Try.NET 內嵌程式代碼執行器和遊樂場的 當地時區 為國際標準時間或 UTC。 這可能會影響範例的行為和輸出,這些範例說明 DateTime、DateTimeOffset和 TimeZoneInfo 型別及其成員。
您也可以下載一組完整的
備註
在本節中:
我呼叫哪一種方法?
自 | 叫 |
---|---|
使用目前文化特性的慣例來剖析日期和時間字串。 | Parse(String) 多載 |
使用特定文化特性的慣例來剖析日期和時間字串。 | Parse(String, IFormatProvider) 多載(請參閱 剖析和文化慣例) |
剖析具有特殊樣式元素的日期和時間字串(例如空格符或無空格符)。 | Parse(String, IFormatProvider, DateTimeStyles) 多載 |
剖析必須具有特定格式的日期和時間字串。 | DateTime.ParseExact 或 DateTime.TryParseExact |
剖析日期和時間字串,並執行UTC或當地時間的轉換。 | Parse(String, IFormatProvider, DateTimeStyles) 多載 |
剖析日期和時間字串,而不處理例外狀況。 | DateTime.TryParse 方法 |
還原 (來回) 格式設定作業所建立的日期和時間值。 | 將 「o」 或 「r」 標準格式字串傳遞至 ToString(String) 方法,並使用 DateTimeStyles.RoundtripKind 呼叫 Parse(String, IFormatProvider, DateTimeStyles) 多載 |
跨計算機(以及可能的文化特性)界限,以固定格式剖析日期和時間字串。 | DateTime.ParseExact 或 DateTime.TryParseExact 方法 |
要剖析的字串
Parse 方法會嘗試將日期和時間值的字串表示轉換成其相等的 DateTime。 它會嘗試完全剖析輸入字串,而不會擲回 FormatException 例外狀況。
重要
如果剖析作業因為無法辨識的字串格式而失敗,則 Parse 方法會擲回 FormatException,而 TryParse 方法會傳回 false
。 因為例外狀況處理可能很昂貴,因此當剖析作業預期成功時,您應該使用 Parse,因為輸入來源是信任的。 剖析失敗時最好 TryParse,特別是因為輸入來源不受信任,或者您有合理的預設值來替代無法成功剖析的字串。
要剖析的字串可以採用下列任何形式:
具有日期和時間元件的字串。
具有日期但沒有時間元件的字串。 如果時間元件不存在,方法會假設午夜為 12:00。 如果日期元件有兩位數的年份,則會根據目前文化特性的目前行事曆或指定文化特性的目前行事曆 Calendar.TwoDigitYearMax 轉換成年份(如果您使用多載搭配非 Null
provider
自變數)。包含日期元件的字串,只包含月份和年份,但沒有日期元件。 方法假設當月的第一天。
包含日期元件的字串,只包含月份和日期,但不含年份元件。 方法會假設目前的年份。
具有時間但沒有日期元件的字串。 除非您呼叫 Parse(String, IFormatProvider, DateTimeStyles) 多載,並在
styles
自變數中包含 DateTimeStyles.NoCurrentDateDefault,否則方法會假設目前日期為 0001 年 1 月 1 日。包含時間元件的字串,只包含小時和AM/PM指示項,不含日期元件。 方法假設目前的日期和時間沒有分鐘和秒。 您可以呼叫 Parse(String, IFormatProvider, DateTimeStyles) 多載來變更此行為,並在
styles
自變數中包含 DateTimeStyles.NoCurrentDateDefault,在此情況下,方法會假設日期為 0001 年 1 月 1 日。包含時區資訊的字串,且符合 ISO 8601。 在下列範例中,第一個字串會指定國際標準時間 (UTC),第二個字串會指定比 UTC 早七個小時的時區時間:
“2008-11-01T19:35:00.00000000Z” “2008-11-01T19:35:00.000000-07:00”
包含 GMT 指示項且符合 RFC 1123 時間格式的字串;例如:
“Sat, 01 Nov 2008 19:35:00 GMT”
包含日期和時間以及時區位移資訊的字串;例如:
"03/01/2009 05:42:00 -5:00"
下列範例會使用目前文化特性的格式慣例來剖析每一種格式的字元串,在此案例中為 en-US 文化特性:
using System;
public class Example
{
public static void Main()
{
(string dateAsString, string description)[] dateInfo = { ("08/18/2018 07:22:16", "String with a date and time component"),
("08/18/2018", "String with a date component only"),
("8/2018", "String with a month and year component only"),
("8/18", "String with a month and day component only"),
("07:22:16", "String with a time component only"),
("7 PM", "String with an hour and AM/PM designator only"),
("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),
("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) };
Console.WriteLine($"Today is {DateTime.Now:d}\n");
foreach (var item in dateInfo) {
Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}");
}
}
}
// The example displays output like the following:
// Today is 2/22/2018
//
// String with a date and time component: '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
// String with a date component only: '08/18/2018' --> 8/18/2018 12:00:00 AM
// String with a month and year component only: '8/2018' --> 8/1/2018 12:00:00 AM
// String with a month and day component only: '8/18' --> 8/18/2018 12:00:00 AM
// String with a time component only: '07:22:16' --> 2/22/2018 7:22:16 AM
// String with an hour and AM/PM designator only: '7 PM' --> 2/22/2018 7:00:00 PM
// UTC string that conforms to ISO 8601: '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
// Non-UTC string that conforms to ISO 8601: '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
// String that conforms to RFC 1123: 'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
// String with date, time, and time zone information: '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM
module Parse6
open System
let dateInfo =
[ "08/18/2018 07:22:16", "String with a date and time component"
"08/18/2018", "String with a date component only"
"8/2018", "String with a month and year component only"
"8/18", "String with a month and day component only"
"07:22:16", "String with a time component only"
"7 PM", "String with an hour and AM/PM designator only"
"2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"
"2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"
"Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"
"08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ]
printfn $"Today is {DateTime.Now:d}\n"
for dateAsString, description in dateInfo do
printfn $"""{description + ":",-52} '{dateAsString}' --> {DateTime.Parse(dateAsString)}"""
// The example displays output like the following:
// Today is 2/22/2018
//
// String with a date and time component: '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
// String with a date component only: '08/18/2018' --> 8/18/2018 12:00:00 AM
// String with a month and year component only: '8/2018' --> 8/1/2018 12:00:00 AM
// String with a month and day component only: '8/18' --> 8/18/2018 12:00:00 AM
// String with a time component only: '07:22:16' --> 2/22/2018 7:22:16 AM
// String with an hour and AM/PM designator only: '7 PM' --> 2/22/2018 7:00:00 PM
// UTC string that conforms to ISO 8601: '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
// Non-UTC string that conforms to ISO 8601: '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
// String that conforms to RFC 1123: 'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
// String with date, time, and time zone information: '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM
Public Module Strings
Public Sub Main()
Dim dateInfo() As (dateAsString As String, description As String) =
{ ("08/18/2018 07:22:16", "String with a date and time component"),
("08/18/2018", "String with a date component only"),
("8/2018", "String with a month and year component only"),
("8/18", "String with a month and day component only"),
("07:22:16", "String with a time component only"),
("7 PM", "String with an hour and AM/PM designator only"),
("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),
("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) }
Console.WriteLine($"Today is {Date.Now:d}{vbCrLf}")
For Each item in dateInfo
Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}")
Next
End Sub
End Module
' The example displays output like the following:
' Today is 2/22/2018
'
' String with a date and time component: '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
' String with a date component only: '08/18/2018' --> 8/18/2018 12:00:00 AM
' String with a month and year component only: '8/2018' --> 8/1/2018 12:00:00 AM
' String with a month and day component only: '8/18' --> 8/18/2018 12:00:00 AM
' String with a time component only: '07:22:16' --> 2/22/2018 7:22:16 AM
' String with an hour and AM/PM designator only: '7 PM' --> 2/22/2018 7:00:00 PM
' UTC string that conforms to ISO 8601: '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
' Non-UTC string that conforms to ISO 8601: '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
' String that conforms to RFC 1123: 'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
' String with date, time, and time zone information: '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM
如果輸入字串代表剖析方法所使用的日曆中閏年的閏日(請參閱 剖析和文化慣例),則 Parse 方法會成功剖析字元串。 如果輸入字串代表非閏年的閏日,此方法會擲回 FormatException。
由於 Parse 方法會嘗試使用目前或指定文化特性的格式規則來剖析日期和時間的字串表示法,因此嘗試剖析不同文化特性的字串可能會失敗。 若要跨不同地區設定剖析特定的日期和時間格式,請使用 DateTime.ParseExact 方法的其中一個多載,並提供格式規範。
剖析和文化慣例
除非要剖析的字串符合 ISO 8601 模式 s
,否則 Parse 方法的所有多載都會區分文化特性。 剖析作業會使用衍生 DateTimeFormatInfo 物件中的格式資訊,如下所示:
重要
日本日曆中的紀元基於皇帝的統治,因此預計將改變。 例如,2019 年 5 月 1 日在 JapaneseCalendar 和 JapaneseLunisolarCalendar中標示了 Reiwa 時代的開頭。 這種時代變更會影響使用這些行事曆的所有應用程式。 如需詳細資訊,以及判斷您的應用程式是否受到影響,請參閱 處理 .NET 中日曆中的新紀元。 如需在 Windows 系統上測試應用程式,以確保其整備時代變更的相關信息,請參閱 準備您的應用程式以取得日文時代變更。 如需 .NET 中支援具有多個紀元的行事曆功能,以及使用支援多個紀元的行事歷時的最佳作法,請參閱 使用紀元。
當格式化資訊衍生自 DateTimeFormatInfo 物件時,DateTimeFormatInfo.Calendar 屬性會定義剖析作業中使用的行事曆。
如果您使用 DateTimeFormatInfo 與標準文化特性不同的自訂設定來剖析日期和時間字元串,請使用 ParseExact 方法,而不是使用 Parse 方法來改善成功轉換的機會。 非標準日期和時間字串可能很複雜且難以剖析。
Parse 方法會嘗試剖析具有數個隱含剖析模式的字串,這一切可能會失敗。 相反地,ParseExact 方法會要求您明確指定一或多個可能成功的確切剖析模式。 如需詳細資訊,請參閱
重要
請注意,特定文化特性的格式設定慣例是動態的,而且可能會變更。 這表示剖析作業取決於預設 (目前) 文化特性的格式設定慣例,或指定代表非變異文化特性之文化特性的 IFormatProvider 物件,如果發生下列任一情況,可能會意外失敗:
- 特定文化特性的數據在 .NET Framework 的主要或次要版本之間有所變更,或因為更新為現有 .NET Framework 版本的結果。
- 特定文化特性數據反映使用者喜好設定,可能會因計算機或會話而異。
- 特定文化特性數據代表取代文化特性,該文化特性會覆寫標準文化特性或自定義文化特性的設定。
若要避免剖析與文化數據變更相關聯之數據和時間字串的困難,您可以使用不因文化特性而異來剖析日期和時間字串,或者您可以呼叫 ParseExact 或 TryParseExact 方法,並指定要剖析的字元串確切格式。 如果您要串行化和還原串行化日期和時間數據,您可以使用不因文化特性而異的格式設定慣例,也可以以二進位格式串行化和還原串行化 DateTime 值。
如需詳細資訊,請參閱 CultureInfo 主題中的一節和 DateTime 主題中的一節。
剖析和樣式專案
所有 Parse 多載都會忽略輸入字串中的前置、內部或尾端空格符(下表中以 s
表示)。 日期和時間可以加上一對開頭和尾端的 NUMBER SIGN 字元(“#”,U+0023),而且可以以一或多個 NULL 字元(U+0000) 結尾。
此外,Parse(String, IFormatProvider, DateTimeStyles) 多載具有由一或多個 DateTimeStyles 列舉成員組成的 styles
參數。 此參數會定義應該如何解譯 s
,以及剖析作業如何將 s
轉換成日期和時間。 下表描述剖析作業上每個 DateTimeStyles 成員的效果。
DateTimeStyles 成員 | 轉換的效果 |
---|---|
AdjustToUniversal | 剖析 s ,並視需要將其轉換成 UTC,如下所示:- 如果 s 包含時區位移,或如果 s 不包含時區資訊,但 styles 包含 AssumeLocal 旗標,則方法會剖析字串、呼叫 ToUniversalTime 將傳回 DateTime 值轉換為 UTC,並將 Kind 屬性設定為 DateTimeKind.Utc。- 如果 s 表示它代表 UTC,或者如果 s 不包含時區資訊,但 styles 包含 AssumeUniversal 旗標,則方法會剖析字串、在傳回 DateTime 值上執行任何時區轉換,並將 Kind 屬性設定為 DateTimeKind.Utc。- 在其他所有情況下,旗標沒有任何作用。 |
AllowInnerWhite | 這個值會被忽略。
s 的日期和時間元素中一律允許內部空格符。 |
AllowLeadingWhite | 這個值會被忽略。 在 s 的日期和時間元素中,一律允許前置空格符。 |
AllowTrailingWhite | 這個值會被忽略。 在 s 的日期和時間元素中,一律允許尾端空格符。 |
AllowWhiteSpaces | 指定 s 可能包含前置、內部和尾端空格符。 這是預設行為。 藉由提供更嚴格的 DateTimeStyles 列舉值,例如 None,便無法覆寫它。 |
AssumeLocal | 指定如果 s 缺少任何時區資訊,則會假設當地時間。 除非 AdjustToUniversal 旗標存在,否則傳回 DateTime 值的 Kind 屬性會設定為 DateTimeKind.Local。 |
AssumeUniversal | 指定如果 s 缺少任何時區資訊,則會假設 UTC。 除非 AdjustToUniversal 旗標存在,否則 方法會將傳回 DateTime 值從UTC轉換為當地時間,並將其 Kind 屬性設定為 DateTimeKind.Local。 |
None | 雖然有效,但會忽略此值。 |
RoundtripKind | 針對包含時區資訊的字串,嘗試防止將日期和時間字串轉換成 DateTime 值,這個值代表其 Kind 屬性設定為 DateTimeKind.Local。 一般而言,這類字串是藉由呼叫 DateTime.ToString(String) 方法,並使用 「o」、“r” 或 “u” 標準格式規範來建立。 |
傳回值和 DateTime.Kind
DateTime.Parse
多載會傳回 DateTime 值,其 Kind 屬性包含時區資訊。 它可以指出時間是:
- 國際標準時間(System.DateTimeKind.Utc)。
- 當地時區的時間(System.DateTimeKind.Local)。
- 未知時區的時間(System.DateTimeKind.Unspecified)。
一般而言,Parse 方法會傳回 Kind 屬性為 DateTimeKind.Unspecified的 DateTime 物件。 不過,Parse 方法也可能執行時區轉換,並根據 s
和 styles
參數的值,以不同的方式設定 Kind 屬性的值:
如果 | 時區轉換 | Kind 屬性 |
---|---|---|
s 包含時區資訊。 |
日期和時間會轉換成當地時區中的時間。 | DateTimeKind.Local |
s 包含時區資訊,styles 包含 AdjustToUniversal 旗標。 |
日期和時間會轉換成國際標準時間(UTC)。 | DateTimeKind.Utc |
s 包含 Z 或 GMT 時區指示項,styles 包含 RoundtripKind 旗標。 |
日期和時間會解譯為UTC。 | DateTimeKind.Utc |
下列範例會將包含時區資訊的日期字串轉換成當地時區中的時間:
using System;
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine($"Converted {dateString} to {convertedDate.Kind} time {convertedDate}");
}
}
}
// These calls to the DateTime.Parse method display the following output:
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
open System
let dateStrings =
[ "2008-05-01T07:34:42-5:00"
"2008-05-01 7:34:42Z"
"Thu, 01 May 2008 07:34:42 GMT" ]
for dateString in dateStrings do
let convertedDate = DateTime.Parse dateString
printfn $"Converted {dateString} to {convertedDate.Kind} time {convertedDate}"
// These calls to the DateTime.Parse method display the following output:
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
Module Example
Public Sub Main()
Dim dateStrings() As String = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"}
For Each dateStr In dateStrings
Dim convertedDate As Date = Date.Parse(dateStr)
Console.WriteLine($"Converted {dateStr} to {convertedDate.Kind} time {convertedDate}")
Next
End Sub
End Module
' These calls to the DateTime.Parse method display the following output:
' Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
' Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
' Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
您也可以使用 DateTimeStyles.RoundtripKind 旗標,在格式化和剖析作業期間保留日期和時間 Kind 屬性的值。 下列範例說明 RoundtripKind 旗標如何影響 DateTime 值上的剖析作業,這些值會使用 「o」、“r” 或 “u” 格式規範轉換成字串。
string[] formattedDates = { "2008-09-15T09:30:41.7752486-07:00",
"2008-09-15T09:30:41.7752486Z",
"2008-09-15T09:30:41.7752486",
"2008-09-15T09:30:41.7752486-04:00",
"Mon, 15 Sep 2008 09:30:41 GMT" };
foreach (string formattedDate in formattedDates)
{
Console.WriteLine(formattedDate);
DateTime roundtripDate = DateTime.Parse(formattedDate, null,
DateTimeStyles.RoundtripKind);
Console.WriteLine($" With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.");
DateTime noRoundtripDate = DateTime.Parse(formattedDate, null,
DateTimeStyles.None);
Console.WriteLine($" Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.");
}
// The example displays the following output:
// 2008-09-15T09:30:41.7752486-07:00
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
// Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
// 2008-09-15T09:30:41.7752486Z
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
// Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
// 2008-09-15T09:30:41.7752486
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
// Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
// 2008-09-15T09:30:41.7752486-04:00
// With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
// Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
// Mon, 15 Sep 2008 09:30:41 GMT
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
// Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
let formattedDates =
[ "2008-09-15T09:30:41.7752486-07:00"
"2008-09-15T09:30:41.7752486Z"
"2008-09-15T09:30:41.7752486"
"2008-09-15T09:30:41.7752486-04:00"
"Mon, 15 Sep 2008 09:30:41 GMT" ]
for formattedDate in formattedDates do
printfn $"{formattedDate}"
let roundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.RoundtripKind)
printfn $" With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time."
let noRoundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.None)
printfn $" Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time."
// The example displays the following output:
// 2008-09-15T09:30:41.7752486-07:00
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
// Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
// 2008-09-15T09:30:41.7752486Z
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
// Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
// 2008-09-15T09:30:41.7752486
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
// Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
// 2008-09-15T09:30:41.7752486-04:00
// With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
// Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
// Mon, 15 Sep 2008 09:30:41 GMT
// With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
// Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
Dim formattedDates() = { "2008-09-15T09:30:41.7752486-07:00",
"2008-09-15T09:30:41.7752486Z",
"2008-09-15T09:30:41.7752486",
"2008-09-15T09:30:41.7752486-04:00",
"Mon, 15 Sep 2008 09:30:41 GMT" }
For Each formattedDate In formattedDates
Console.WriteLine(formattedDate)
Dim roundtripDate = DateTime.Parse(formattedDate, Nothing,
DateTimeStyles.RoundtripKind)
Console.WriteLine($" With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.")
Dim noRoundtripDate = DateTime.Parse(formattedDate, Nothing, DateTimeStyles.None)
Console.WriteLine($" Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.")
Next
' The example displays the following output:
' 2008-09-15T09:30:41.7752486-07:00
' With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
' Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
' 2008-09-15T09:30:41.7752486Z
' With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
' Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
' 2008-09-15T09:30:41.7752486
' With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
' Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
' 2008-09-15T09:30:41.7752486-04:00
' With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
' Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
' Mon, 15 Sep 2008 09:30:41 GMT
' With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
' Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
Parse(String)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
使用目前文化特性的慣例,將日期和時間的字串表示轉換為其相等的 DateTime。
public:
static DateTime Parse(System::String ^ s);
public static DateTime Parse (string s);
static member Parse : string -> DateTime
Public Shared Function Parse (s As String) As DateTime
參數
傳回
對象,相當於 s
中包含的日期和時間。
例外狀況
s
null
。
s
不包含日期和時間的有效字串表示。
範例
下列範例會剖析數個日期和時間值的字串表示方式:
使用預設格式提供者,提供計算機目前用來產生範例輸出之文化特性的格式慣例。 此範例的輸出會反映 en-US 文化特性的格式設定慣例。
使用預設樣式值,AllowWhiteSpaces。
它會處理當 方法嘗試使用其他文化特性的格式慣例剖析日期和時間的字串表示法時,所擲回的 FormatException 例外狀況。 它也會示範如何成功剖析未使用目前文化特性之格式設定慣例的日期和時間值。
using System;
using System.Globalization;
public class DateTimeParser
{
public static void Main()
{
// Assume the current culture is en-US.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
// Use standard en-US date and time value
DateTime dateValue;
string dateString = "2/16/2008 12:15:12 PM";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
// Reverse month and day to conform to the fr-FR culture.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
dateString = "16/02/2008 12:15:12";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
// Call another overload of Parse to successfully convert string
// formatted according to conventions of fr-FR culture.
try {
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
// Parse string with date but no time component.
dateString = "2/16/2008";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
}
}
// The example displays the following output to the console:
// '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
// Unable to convert '16/02/2008 12:15:12'.
// '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
// '2/16/2008' converted to 2/16/2008 12:00:00 AM.
open System
open System.Globalization
[<EntryPoint>]
let main _ =
// Assume the current culture is en-US.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
// Use standard en-US date and time value
let dateString = "2/16/2008 12:15:12 PM"
try
let dateValue = DateTime.Parse dateString
printfn $"'{dateString}' converted to {dateValue}."
with :? FormatException ->
printfn $"Unable to convert '{dateString}'."
// Reverse month and day to conform to the fr-FR culture.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
let dateString = "16/02/2008 12:15:12"
try
let dateValue = DateTime.Parse dateString
printfn $"'{dateString}' converted to {dateValue}."
with :? FormatException ->
Console.WriteLine("Unable to convert '{0}'.", dateString)
// Call another overload of Parse to successfully convert string
// formatted according to conventions of fr-FR culture.
try
let dateValue = DateTime.Parse(dateString, CultureInfo("fr-FR", false))
printfn $"'{dateString}' converted to {dateValue}."
with :? FormatException ->
printfn $"Unable to convert '{dateString}'."
// Parse string with date but no time component.
let dateString = "2/16/2008"
try
let dateValue = DateTime.Parse dateString
printfn $"'{dateString}' converted to {dateValue}."
with :? FormatException ->
printfn $"Unable to convert '{dateString}'."
0
// The example displays the following output to the console:
// '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
// Unable to convert '16/02/2008 12:15:12'.
// '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
// '2/16/2008' converted to 2/16/2008 12:00:00 AM.
Imports System.Globalization
Class DateTimeParser
Public Shared Sub Main()
' Assume the current culture is en-US.
' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
' Use standard en-US date and time value
Dim dateValue As Date
Dim dateString As String = "2/16/2008 12:15:12 PM"
Try
dateValue = Date.Parse(dateString)
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}'.", dateString)
End Try
' Reverse month and day to conform to the fr-FR culture.
' The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
dateString = "16/02/2008 12:15:12"
Try
dateValue = Date.Parse(dateString)
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}'.", dateString)
End Try
' Call another overload of Parse to successfully convert string
' formatted according to conventions of fr-FR culture.
Try
dateValue = Date.Parse(dateString, New CultureInfo("fr-FR", False))
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}'.", dateString)
End Try
' Parse string with date but no time component.
dateString = "2/16/2008"
Try
dateValue = Date.Parse(dateString)
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
Catch e As FormatException
Console.WriteLine("Unable to convert '{0}'.", dateString)
End Try
End Sub
End Class
' The example displays the following output to the console:
' '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM.
' Unable to convert '16/02/2008 12:15:12'.
' '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM.
' '2/16/2008' converted to 2/16/2008 12:00:00 AM.
備註
如果 s
包含時區資訊,這個方法會傳回 DateTime 值,其 Kind 屬性是 DateTimeKind.Local,並將 s
中的日期和時間轉換成當地時間。 否則,它不會執行時區轉換,並傳回 DateTime 值,其 Kind 屬性為 DateTimeKind.Unspecified。
此多載會使用目前文化特性的格式慣例,嘗試剖析 s
。 目前的文化特性是由 CurrentCulture 屬性表示。 若要使用特定文化特性的格式慣例剖析字串,請呼叫 Parse(String, IFormatProvider) 或 Parse(String, IFormatProvider, DateTimeStyles) 多載。
此多載會嘗試使用 DateTimeStyles.AllowWhiteSpaces 樣式剖析 s
。
另請參閱
適用於
Parse(ReadOnlySpan<Char>, IFormatProvider)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
將字元範圍剖析為值。
public:
static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<DateTime>::Parse;
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As DateTime
參數
- s
- ReadOnlySpan<Char>
要剖析的字元範圍。
- provider
- IFormatProvider
物件,提供與 s
相關的特定文化特性格式資訊。
傳回
剖析 s
的結果。
實作
適用於
Parse(String, IFormatProvider)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
使用特定文化特性格式資訊,將日期和時間的字串表示轉換成其相等 DateTime。
public:
static DateTime Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static DateTime Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<DateTime>::Parse;
public static DateTime Parse (string s, IFormatProvider provider);
public static DateTime Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider) As DateTime
參數
- provider
- IFormatProvider
物件,提供與 s
相關的特定文化特性格式資訊。 請參閱 剖析和文化慣例
傳回
對象,相當於 provider
所指定之 s
中包含的日期和時間。
實作
例外狀況
s
null
。
s
不包含日期和時間的有效字串表示。
範例
下列範例會使用 en-US、fr-FR和 de-DE 文化特性的慣例來剖析日期字串數位。 它示範單一日期的字串表示可以不同文化特性以不同的方式解譯。
using System;
using System.Globalization;
public class ParseDate
{
public static void Main()
{
// Define cultures to be used to parse dates.
CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("de-DE")};
// Define string representations of a date to be parsed.
string[] dateStrings = {"01/10/2009 7:34 PM",
"10.01.2009 19:34",
"10-1-2009 19:34" };
// Parse dates using each culture.
foreach (CultureInfo culture in cultures)
{
DateTime dateValue;
Console.WriteLine("Attempted conversions using {0} culture.",
culture.Name);
foreach (string dateString in dateStrings)
{
try {
dateValue = DateTime.Parse(dateString, culture);
Console.WriteLine(" Converted '{0}' to {1}.",
dateString, dateValue.ToString("f", culture));
}
catch (FormatException) {
Console.WriteLine(" Unable to convert '{0}' for culture {1}.",
dateString, culture.Name);
}
}
Console.WriteLine();
}
}
}
// The example displays the following output to the console:
// Attempted conversions using en-US culture.
// Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
// Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
// Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//
// Attempted conversions using fr-FR culture.
// Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
// Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
// Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
//
// Attempted conversions using de-DE culture.
// Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
// Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
// Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
open System
open System.Globalization
// Define cultures to be used to parse dates.
let cultures =
[ CultureInfo.CreateSpecificCulture "en-US"
CultureInfo.CreateSpecificCulture "fr-FR"
CultureInfo.CreateSpecificCulture "de-DE" ]
// Define string representations of a date to be parsed.
let dateStrings =
[ "01/10/2009 7:34 PM"
"10.01.2009 19:34"
"10-1-2009 19:34" ]
// Parse dates using each culture.
for culture in cultures do
printfn $"Attempted conversions using {culture.Name} culture."
for dateString in dateStrings do
try
let dateValue = DateTime.Parse(dateString, culture)
printfn $""" Converted '{dateString}' to {dateValue.ToString("f", culture)}."""
with :? FormatException ->
printfn $" Unable to convert '{dateString}' for culture {culture.Name}."
printfn ""
// The example displays the following output to the console:
// Attempted conversions using en-US culture.
// Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
// Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
// Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
//
// Attempted conversions using fr-FR culture.
// Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
// Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
// Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
//
// Attempted conversions using de-DE culture.
// Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
// Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
// Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
Imports System.Globalization
Module ParseDate
Public Sub Main()
' Define cultures to be used to parse dates.
Dim cultures() As CultureInfo = {CultureInfo.CreateSpecificCulture("en-US"), _
CultureInfo.CreateSpecificCulture("fr-FR"), _
CultureInfo.CreateSpecificCulture("de-DE")}
' Define string representations of a date to be parsed.
Dim dateStrings() As String = {"01/10/2009 7:34 PM", _
"10.01.2009 19:34", _
"10-1-2009 19:34" }
' Parse dates using each culture.
For Each culture In cultures
Dim dateValue As Date
Console.WriteLine("Attempted conversions using {0} culture.", culture.Name)
For Each dateString As String In dateStrings
Try
dateValue = Date.Parse(dateString, culture)
Console.WriteLine(" Converted '{0}' to {1}.", _
dateString, dateValue.ToString("f", culture))
Catch e As FormatException
Console.WriteLine(" Unable to convert '{0}' for culture {1}.", _
dateString, culture.Name)
End Try
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output to the console:
' Attempted conversions using en-US culture.
' Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM.
' Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM.
' Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM.
'
' Attempted conversions using fr-FR culture.
' Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34.
' Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34.
' Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34.
'
' Attempted conversions using de-DE culture.
' Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34.
' Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34.
' Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.
備註
如果 s
包含時區資訊,這個方法會傳回 DateTime 值,其 Kind 屬性是 DateTimeKind.Local,並將 s
中的日期和時間轉換成當地時間。 否則,它不會執行時區轉換,並傳回 DateTime 值,其 Kind 屬性為 DateTimeKind.Unspecified。
此多載會嘗試使用 DateTimeStyles.AllowWhiteSpaces 樣式剖析 s
。
另請參閱
適用於
Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
使用特定文化特性格式資訊和格式樣式,將包含日期和時間字串表示的記憶體範圍轉換為其相等的 DateTime。
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider = default, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider provider = default, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member Parse : ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional provider As IFormatProvider = Nothing, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime
參數
- s
- ReadOnlySpan<Char>
包含要剖析之字串的記憶體範圍。 如需詳細資訊,請參閱 剖析 字串。
- provider
- IFormatProvider
物件,提供與 s
相關的特定文化特性格式資訊。 請參閱 剖析和文化慣例
- styles
- DateTimeStyles
列舉值的位元組合,表示剖析作業成功 s
中可以存在的樣式專案,並定義如何解譯與目前時區或目前日期相關的剖析日期。 要指定的一般值是 None。
傳回
對象,相當於 s
中包含的日期和時間,如 provider
和 styles
所指定。
例外狀況
s
不包含日期和時間的有效字串表示。
styles
包含無效的 DateTimeStyles 值組合。 例如,AssumeLocal 和 AssumeUniversal。
適用於
Parse(String, IFormatProvider, DateTimeStyles)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
使用特定文化特性格式資訊和格式樣式,將日期和時間的字串表示轉換為其相等的 DateTime。
public:
static DateTime Parse(System::String ^ s, IFormatProvider ^ provider, System::Globalization::DateTimeStyles styles);
public static DateTime Parse (string s, IFormatProvider provider, System.Globalization.DateTimeStyles styles);
public static DateTime Parse (string s, IFormatProvider? provider, System.Globalization.DateTimeStyles styles);
static member Parse : string * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider, styles As DateTimeStyles) As DateTime
參數
- provider
- IFormatProvider
物件,提供與 s
相關的特定文化特性格式資訊。 請參閱 剖析和文化慣例
- styles
- DateTimeStyles
列舉值的位元組合,表示剖析作業成功 s
中可以存在的樣式專案,並定義如何解譯與目前時區或目前日期相關的剖析日期。 要指定的一般值是 None。
傳回
對象,相當於 s
中包含的日期和時間,如 provider
和 styles
所指定。
例外狀況
s
null
。
s
不包含日期和時間的有效字串表示。
styles
包含無效的 DateTimeStyles 值組合。 例如,AssumeLocal 和 AssumeUniversal。
範例
下列範例示範 Parse(String, IFormatProvider, DateTimeStyles) 方法,並顯示所產生 DateTime 值的 Kind 屬性值。
using System;
using System.Globalization;
public class ParseDateExample
{
public static void Main()
{
string dateString;
CultureInfo culture ;
DateTimeStyles styles;
DateTime result;
// Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM";
culture = CultureInfo.CreateSpecificCulture("en-US");
styles = DateTimeStyles.None;
try {
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException) {
Console.WriteLine("Unable to convert {0} to a date and time.",
dateString);
}
// Parse the same date and time with the AssumeLocal style.
styles = DateTimeStyles.AssumeLocal;
try {
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException) {
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}
// Parse a date and time that is assumed to be local.
// This time is five hours behind UTC. The local system's time zone is
// eight hours behind UTC.
dateString = "2009/03/01T10:00:00-5:00";
styles = DateTimeStyles.AssumeLocal;
try {
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException) {
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}
// Attempt to convert a string in improper ISO 8601 format.
dateString = "03/01/2009T10:00:00-5:00";
try {
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException) {
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}
// Assume a date and time string formatted for the fr-FR culture is the local
// time and convert it to UTC.
dateString = "2008-03-01 10:00";
culture = CultureInfo.CreateSpecificCulture("fr-FR");
styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
try {
result = DateTime.Parse(dateString, culture, styles);
Console.WriteLine("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString());
}
catch (FormatException) {
Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
}
}
}
// The example displays the following output to the console:
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
// 2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
// Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
// 2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
open System
open System.Globalization
[<EntryPoint>]
let main _ =
// Parse a date and time with no styles.
let dateString = "03/01/2009 10:00 AM"
let culture = CultureInfo.CreateSpecificCulture "en-US"
let styles = DateTimeStyles.None
try
let result = DateTime.Parse(dateString, culture, styles)
printfn $"{dateString} converted to {result} {result.Kind}."
with :? FormatException ->
printfn $"Unable to convert {dateString} to a date and time."
// Parse the same date and time with the AssumeLocal style.
let styles = DateTimeStyles.AssumeLocal
try
let result = DateTime.Parse(dateString, culture, styles)
printfn $"{dateString} converted to {result} {result.Kind}."
with :? FormatException ->
printfn $"Unable to convert {dateString} to a date and time."
// Parse a date and time that is assumed to be local.
// This time is five hours behind UTC. The local system's time zone is
// eight hours behind UTC.
let dateString = "2009/03/01T10:00:00-5:00"
let styles = DateTimeStyles.AssumeLocal
try
let result = DateTime.Parse(dateString, culture, styles)
printfn $"{dateString} converted to {result} {result.Kind}."
with :? FormatException ->
printfn $"Unable to convert {dateString} to a date and time."
// Attempt to convert a string in improper ISO 8601 format.
let dateString = "03/01/2009T10:00:00-5:00"
try
let result = DateTime.Parse(dateString, culture, styles)
printfn $"{dateString} converted to {result} {result.Kind}."
with :? FormatException ->
printfn $"Unable to convert {dateString} to a date and time."
// Assume a date and time string formatted for the fr-FR culture is the local
// time and convert it to UTC.
let dateString = "2008-03-01 10:00"
let culture = CultureInfo.CreateSpecificCulture "fr-FR"
let styles = DateTimeStyles.AdjustToUniversal ||| DateTimeStyles.AssumeLocal
try
let result = DateTime.Parse(dateString, culture, styles)
printfn $"{dateString} converted to {result} {result.Kind}."
with :? FormatException ->
printfn $"Unable to convert {dateString} to a date and time."
0
// The example displays the following output to the console:
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
// 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
// 2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
// Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
// 2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
Imports System.Globalization
Module ParseDateExample
Public Sub Main()
Dim dateString As String
Dim culture As CultureInfo
Dim styles As DateTimeStyles
Dim result As DateTime
' Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM"
culture = CultureInfo.CreateSpecificCulture("en-US")
styles = DateTimeStyles.None
Try
result = DateTime.Parse(dateString, culture, styles)
Console.WriteLine("{0} converted to {1} {2}.", _
dateString, result, result.Kind.ToString())
Catch e As FormatException
Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
End Try
' Parse the same date and time with the AssumeLocal style.
styles = DateTimeStyles.AssumeLocal
Try
result = DateTime.Parse(dateString, culture, styles)
Console.WriteLine("{0} converted to {1} {2}.", _
dateString, result, result.Kind.ToString())
Catch e As FormatException
Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
End Try
' Parse a date and time that is assumed to be local.
' This time is five hours behind UTC. The local system's time zone is
' eight hours behind UTC.
dateString = "2009/03/01T10:00:00-5:00"
styles = DateTimeStyles.AssumeLocal
Try
result = DateTime.Parse(dateString, culture, styles)
Console.WriteLine("{0} converted to {1} {2}.", _
dateString, result, result.Kind.ToString())
Catch e As FormatException
Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
End Try
' Attempt to convert a string in improper ISO 8601 format.
dateString = "03/01/2009T10:00:00-5:00"
Try
result = DateTime.Parse(dateString, culture, styles)
Console.WriteLine("{0} converted to {1} {2}.", _
dateString, result, result.Kind.ToString())
Catch e As FormatException
Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
End Try
' Assume a date and time string formatted for the fr-FR culture is the local
' time and convert it to UTC.
dateString = "2008-03-01 10:00"
culture = CultureInfo.CreateSpecificCulture("fr-FR")
styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
Try
result = DateTime.Parse(dateString, culture, styles)
Console.WriteLine("{0} converted to {1} {2}.", _
dateString, result, result.Kind.ToString())
Catch e As FormatException
Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
End Try
End Sub
End Module
'
' The example displays the following output to the console:
' 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
' 03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
' 2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
' Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
' 2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
備註
此方法多載會轉換 s
中的日期和時間,並設定傳回 DateTime 值的 Kind 屬性,如下所示:
如果 | 時區轉換 | Kind 屬性 |
---|---|---|
s 不包含時區資訊。 |
沒有。 | DateTimeKind.Unspecified |
s 包含時區資訊。 |
到當地時區的時間 | DateTimeKind.Local |
s 包含時區資訊,styles 包含 DateTimeStyles.AdjustToUniversal 旗標。 |
國際標準時間(UTC) | DateTimeKind.Utc |
s 包含 Z 或 GMT 時區指示項,styles 包含 DateTimeStyles.RoundtripKind。 |
沒有。 | DateTimeKind.Utc |
另請參閱
- TryParse
- CultureInfo
- DateTimeFormatInfo
- .NET Framework 中的剖析日期和時間字串
- 標準日期和時間格式字串
- 自定義日期和時間格式字串
- 如何:往返日期和時間值