DateTime.Parse 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將日期與時間的字串表示轉換為其 DateTime 等價值。
多載
| 名稱 | Description |
|---|---|
| Parse(String) |
利用當前文化的慣例,將日期與時間的字串表示轉換為其 DateTime 等價值。 |
| Parse(ReadOnlySpan<Char>, IFormatProvider) |
將字元範圍剖析為值。 |
| Parse(String, IFormatProvider) |
利用文化特定的格式資訊,將日期與時間的字串表示轉換為其 DateTime 等效值。 |
| Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) |
透過使用文化特定的格式資訊與格式風格,將包含日期與時間字串表示的記憶體範圍轉換為對 DateTime 應的。 |
| Parse(String, IFormatProvider, DateTimeStyles) |
利用特定文化的格式資訊與格式風格,將日期與時間的字串表示轉換為對 DateTime 應的。 |
範例
本篇文章備註區及個別DateTime.Parse過載文件中穿插了許多呼叫此DateTime.Parse方法的範例。
你也可以下載完整的範例集 DateTime.Parse ,這些範例包含在 C# 的 .NET Core 專案中。
備註
在本節中:
我呼叫哪一種方法?
| 自 | 叫 |
|---|---|
| 使用目前文化特性的慣例來剖析日期和時間字串。 | Parse(String) 超載 |
| 使用特定文化特性的慣例來剖析日期和時間字串。 | Parse(String, IFormatProvider) 過載(參見 語法分析與文化慣例) |
| 剖析具有特殊樣式元素的日期和時間字串(例如空格符或無空格符)。 | Parse(String, IFormatProvider, DateTimeStyles) 超載 |
| 剖析必須具有特定格式的日期和時間字串。 | DateTime.ParseExact 或 DateTime.TryParseExact |
| 剖析日期和時間字串,並執行UTC或當地時間的轉換。 | Parse(String, IFormatProvider, DateTimeStyles) 超載 |
| 剖析日期和時間字串,而不處理例外狀況。 | DateTime.TryParse 方法 |
| 還原 (來回) 格式設定作業所建立的日期和時間值。 | 將「o」或「r」標準格式字串傳給方法, ToString(String) 並呼叫 Parse(String, IFormatProvider, DateTimeStyles) 過載 DateTimeStyles.RoundtripKind |
| 跨計算機(以及可能的文化特性)界限,以固定格式剖析日期和時間字串。 | DateTime.ParseExact或方法。DateTime.TryParseExact |
要剖析的字串
此 Parse 方法嘗試將日期與時間值的字串表示轉換為其 DateTime 等價值。 它嘗試完整解析輸入字串而不拋 FormatException 出例外。 當使用接受物件 IFormatProvider 的超載時,將用來解析 StringToParse。 若未提供此類物件, CurrentCulture 則改用。
重要
若解析操作因字串格式未被識別而失敗, Parse 方法會拋出一個 FormatException,而方法 TryParse 則回傳 false。 由於例外處理可能成本高昂,你應該在解析操作預期成功、且輸入來源受信任時使用 Parse 。
TryParse 當解析失敗的可能性很大時,特別是因為輸入來源不被信任,或你有合理的預設值可以替換無法成功解析的字串,這會更為理想。
要剖析的字串可以採用下列任何形式:
具有日期和時間元件的字串。
具有日期但沒有時間元件的字串。 如果時間元件不存在,方法會假設午夜為 12:00。 如果日期成分有兩位數年份,則會根據當前文化的當前曆法或指定文化的當前曆法(若使用帶有非空
provider參數的超載參數)的年份Calendar.TwoDigitYearMax來轉換成年份。包含日期元件的字串,只包含月份和年份,但沒有日期元件。 方法假設當月的第一天。
包含日期元件的字串,只包含月份和日期,但不含年份元件。 方法會假設目前的年份。
具有時間但沒有日期元件的字串。 方法假設當前日期,除非你呼叫 Parse(String, IFormatProvider, DateTimeStyles) 過載並將包含 DateTimeStyles.NoCurrentDateDefault 在
styles參數中,此時方法假設日期為 0001 年 1 月 1 日。包含時間元件的字串,只包含小時和AM/PM指示項,不含日期元件。 方法假設目前的日期和時間沒有分鐘和秒。 你可以透過呼叫 Parse(String, IFormatProvider, DateTimeStyles) 超載並包含 DateTimeStyles.NoCurrentDateDefault 在參數中
styles來改變此行為,此時方法假設日期為 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 方法的超載工具之一並提供格式指定符。
剖析和文化慣例
除非要解析的字串(s如下表所示)符合 ISO 8601 模式,否則所有方法的Parse超載皆為文化敏感。 解析操作使用物件的 DateTimeFormatInfo 格式資訊,導出如下:
重要
日本日曆中的紀元基於皇帝的統治,因此預計將改變。 例如,2019 年 5 月 1 日在 JapaneseCalendar 和 JapaneseLunisolarCalendar中標示了 Reiwa 時代的開頭。 這種時代變更會影響使用這些行事曆的所有應用程式。 如需詳細資訊,以及判斷您的應用程式是否受到影響,請參閱 處理 .NET 中日曆中的新紀元。 如需在 Windows 系統上測試應用程式,以確保其準備迎接時代變更的相關信息,請參閱 準備您的應用程式以取得日本年號變更。 如需 .NET 中支援具有多個紀元的行事曆功能,以及使用支援多個紀元的行事曆時的最佳作法,請參閱 使用紀元。
當格式資訊從 DateTimeFormatInfo 物件衍生時,屬性 DateTimeFormatInfo.Calendar 定義了解析操作中使用的日曆。
如果你使用 DateTimeFormatInfo 與標準文化不同的自訂設定物件來解析日期與時間字串,請使用 ParseExact 方法而非 Parse 方法,以提高成功轉換的機率。 非標準日期和時間字串可能很複雜且難以剖析。 此 Parse 方法嘗試解析包含多個隱含解析模式的字串,但這些模式都可能失敗。 相反地,方法 ParseExact 會要求您明確指定一或多個可能成功的確切剖析模式。 欲了解更多資訊,請參閱主題 DateTimeFormatInfo 中的「DateTimeFormatInfo 與動態資料」章節。
重要
請注意,特定文化特性的格式設定慣例是動態的,而且可能會變更。 這表示依賴預設(目前)文化格式慣例或指定 IFormatProvider 代表非不變文化的物件的解析操作,若發生以下任一情況,可能會意外失敗:
- 特定文化特性的數據在 .NET Framework 的主要或次要版本之間有所變更,或因為更新為現有 .NET Framework 版本的結果。
- 特定文化特性數據反映使用者喜好設定,可能會因計算機或會話而異。
- 特定文化特性數據代表取代文化特性,該文化特性會覆寫標準文化特性或自定義文化特性的設定。
為了避免文化資料變化帶來的資料與時間字串解析困難,你可以使用不變文化來解析日期和時間字串,或者呼叫 ParseExact or TryParseExact 方法並指定要解析字串的精確格式。 如果你要序列化和反序列化日期和時間資料,你可以使用不變文化的格式慣例,或者用二進位格式序列化和反序列化值 DateTime 。
欲了解更多資訊,請參閱主題 CultureInfo 中的「動態文化資料」區塊及「持續存在的日期時間值」區塊 DateTime 。
剖析和樣式專案
所有 Parse 過載都會忽略輸入字串中前置、內空或後置的空白字元(如下 s 表所示)。 日期和時間可以加上一對開頭和尾端的 NUMBER SIGN 字元(“#”,U+0023),而且可以以一或多個 NULL 字元(U+0000) 結尾。
此外, Parse(String, IFormatProvider, DateTimeStyles) 過載有一個 styles 參數,由列舉中的一個或多個成員 DateTimeStyles 組成。 這個參數定義了應如何 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旗標存在,否則傳回值的Kind屬性會設定為DateTime。 |
| AssumeUniversal | 規定若 s 缺乏任何時區資訊,則假設為UTC。 除非AdjustToUniversal旗標存在,否則方法會將DateTime返回的值從 UTC 轉換為當地時間,並將其Kind屬性設定為DateTimeKind.Local。 |
| None | 雖然有效,但會忽略此值。 |
| RoundtripKind | 對於包含時區資訊的字串,會嘗試防止將日期和時間字串轉換成 DateTime 代表當地時間且屬性 Kind 設為 DateTimeKind.Local的值。 通常,這類字串是透過呼叫 DateTime.ToString(String) 方法並使用「o」、「r」或「u」標準格式指定符來建立的。 |
傳回值和 DateTime.Kind
超載回DateTime.ParseDateTime傳的值Kind包含時區資訊。 它可以指出時間是:
- 協調世界時(System.DateTimeKind.Utc)。
- 當地時區的時間(System.DateTimeKind.Local)。
- 未知時區的時間(System.DateTimeKind.Unspecified)。
一般而言,該 Parse 方法回傳 DateTime 一個屬性為 KindDateTimeKind.Unspecified的物件。 然而,該Parse方法也可能執行時區轉換,並根據參數styles的值s不同設定屬性的值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 影響使用「o」、「r」或「u」格式指定符轉換 DateTime 成字串的數值的解析操作。
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.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 一個屬性為 KindDateTimeKind.Unspecified的值。
這種過載試圖透過當前文化的格式慣例來解析 s 。 現今的文化由物業 CurrentCulture 所反映。 若要依照特定文化的格式慣例解析字串,呼叫 或 Parse(String, IFormatProvider) overloads Parse(String, IFormatProvider, DateTimeStyles) 。
這種過載試圖透過風格DateTimeStyles.AllowWhiteSpaces來解析s。
另請參閱
適用於
Parse(ReadOnlySpan<Char>, IFormatProvider)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- 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.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物件。 參見 解析與文化慣例
傳回
一個等價於 中 s 所包含的日期與時間的物件,並由 所指定 provider。
實作
例外狀況
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 一個屬性為 KindDateTimeKind.Unspecified的值。
這種過載嘗試透過風格DateTimeStyles.AllowWhiteSpaces來解析s。
另請參閱
適用於
Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- 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包含的日期與時間,並由 與 styles指定provider。
例外狀況
s 不包含有效的日期與時間字串表示。
styles 包含一個無效的值組合 DateTimeStyles 。 例如,兩者皆AssumeLocalAssumeUniversal為。
適用於
Parse(String, IFormatProvider, DateTimeStyles)
- 來源:
- DateTime.cs
- 來源:
- DateTime.cs
- 來源:
- 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包含的日期與時間,並由 與 styles指定provider。
例外狀況
s 為 null。
s 不包含有效的日期與時間字串表示。
styles 包含一個無效的值組合 DateTimeStyles 。 例如,兩者皆AssumeLocalAssumeUniversal為。
範例
以下範例展示此 Parse(String, IFormatProvider, DateTimeStyles) 方法,並顯示 Kind 所得 DateTime 值的屬性值。
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 並設定 Kind 回傳 DateTime 值的性質如下:
| 如果 | 時區轉換 | 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 中解析日期與時間字串
- 標準日期和時間格式字串
- 自訂日期和時間格式字串
- 操作方法:往返日期與時間值