次の方法で共有


DateTime.Parse メソッド

定義

日付と時刻の文字列形式を等価の DateTime に変換します。

オーバーロード

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 オーバーロードのドキュメントに散在しています。

手記

この記事のいくつかの C# の例は、Try.NET インライン コード ランナーとプレイグラウンドで実行されます。 対話型ウィンドウで例 実行 を実行するを選択します。 コードを実行したら、 を再度実行 選択して、コードを変更し、変更したコードを実行できます。 変更されたコードは、対話型ウィンドウで実行されるか、コンパイルに失敗した場合、対話型ウィンドウにすべての C# コンパイラ エラー メッセージが表示されます。

Try.NET インライン コード ランナーとプレイグラウンドの ローカル タイム ゾーン は、協定世界時 (UTC) です。 これは、DateTimeDateTimeOffset、および TimeZoneInfo 型とそのメンバーを示す例の動作と出力に影響する可能性があります。

C#用の .NET Core プロジェクトに含まれている の例の完全なセットをダウンロードすることもできます。

注釈

このセクションでは、次の操作を行います。

どのメソッドを呼び出しますか?

宛先 呼び出し
現在のカルチャの規則を使用して、日付と時刻の文字列を解析します。 Parse(String) オーバーロード
特定のカルチャの規則を使用して、日付と時刻の文字列を解析します。 Parse(String, IFormatProvider) オーバーロード (解析とカルチャ規則に関するを参照)
日付と時刻の文字列を特殊なスタイル要素 (空白や空白なしなど) で解析します。 Parse(String, IFormatProvider, DateTimeStyles) オーバーロード
特定の形式にする必要がある日付と時刻の文字列を解析します。 DateTime.ParseExact または DateTime.TryParseExact
日付と時刻の文字列を解析し、UTC または現地時刻への変換を実行します。 Parse(String, IFormatProvider, DateTimeStyles) オーバーロード
例外を処理せずに日付と時刻の文字列を解析します。 DateTime.TryParse メソッド
書式設定操作によって作成された日付と時刻の値を復元 (ラウンドトリップ) します。 ToString(String) メソッドに "o" または "r" 標準書式指定文字列を渡し、DateTimeStyles.RoundtripKind を使用して Parse(String, IFormatProvider, DateTimeStyles) オーバーロードを呼び出します。
コンピューター (および場合によってはカルチャ) の境界を越えて、固定形式で日付と時刻の文字列を解析します。 DateTime.ParseExact または DateTime.TryParseExact メソッド

解析する文字列

Parse メソッドは、日付と時刻の値の文字列形式を等価の DateTime に変換しようとします。 FormatException 例外をスローせずに、入力文字列を完全に解析しようとします。

大事な

認識できない文字列形式のために解析操作が失敗した場合、Parse メソッドは FormatExceptionをスローしますが、TryParse メソッドは falseを返します。 例外処理はコストがかかる可能性があるため、入力ソースが信頼されているために解析操作が成功することが予想される場合は、Parse を使用する必要があります。 TryParse は、解析エラーが発生する可能性が高い場合、特に入力ソースが信頼されていない場合や、正常に解析されない文字列に代わる適切な既定値がある場合に適しています。

解析される文字列は、次のいずれかの形式になります。

  • 日付と時刻のコンポーネントを含む文字列。

  • 日付を含むが、時刻コンポーネントを持たない文字列。 時刻コンポーネントが存在しない場合、メソッドは午前 12 時 00 分を想定します。 日付コンポーネントに 2 桁の年がある場合、現在のカルチャの現在のカレンダーまたは指定したカルチャの現在のカレンダーの 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) を指定し、2 番目の文字列は UTC より 7 時間前のタイム ゾーンの時刻を指定します。

    "2008-11-01T19:35:00.0000000Z" "2008-11-01T19:35:00.0000000-07:00"

  • GMT 指定子を含み、RFC 1123 時刻形式に準拠する文字列。例えば:

    "2008 年 11 月 1 日 (土) 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 日は、JapaneseCalendarJapaneseLunisolarCalendarで令和元年の始まりを示しました。 このような時代の変化は、これらのカレンダーを使用するすべてのアプリケーションに影響します。 詳細およびアプリケーションが影響を受けるかどうかを確認するには、「.NETの日本語カレンダーで新しい時代 (年号) を処理する を参照してください。 Windows システム上でアプリケーションをテストして時代 (年号) の変更に対する準備を確認する方法については、「日本の時代 (年号) の変更に対応するためのアプリケーションの準備」を参照してください。 複数の時代 (年号) を含むカレンダーをサポートする .NET の機能と、複数の時代 (年号) をサポートするカレンダーを使用する場合のベスト プラクティスについては、「年号の使用」を参照してください。

呼び出しの場合 provider 書式設定情報は、次の値から派生します。
Parse(String) - 現在のカルチャ (DateTimeFormatInfo.CurrentInfo プロパティ)
Parse(String, IFormatProvider) または Parse(String, IFormatProvider, DateTimeStyles) DateTimeFormatInfo オブジェクト 指定した DateTimeFormatInfo オブジェクト
Parse(String, IFormatProvider) または Parse(String, IFormatProvider, DateTimeStyles) null 現在のカルチャ (DateTimeFormatInfo.CurrentInfo プロパティ)
Parse(String, IFormatProvider) または Parse(String, IFormatProvider, DateTimeStyles) CultureInfo オブジェクト CultureInfo.DateTimeFormat プロパティ
Parse(String, IFormatProvider) または Parse(String, IFormatProvider, DateTimeStyles) カスタム IFormatProvider 実装 IFormatProvider.GetFormat メソッド

書式設定情報が DateTimeFormatInfo オブジェクトから派生する場合、DateTimeFormatInfo.Calendar プロパティは解析操作で使用されるカレンダーを定義します。

標準カルチャとは異なるカスタマイズされた設定を持つ DateTimeFormatInfo オブジェクトを使用して日付と時刻の文字列を解析する場合は、Parse メソッドの代わりに ParseExact メソッドを使用して、変換が成功する可能性を高めます。 標準以外の日付と時刻の文字列は複雑で、解析が困難な場合があります。 Parse メソッドは、いくつかの暗黙的な解析パターンを持つ文字列の解析を試みますが、これらはすべて失敗する可能性があります。 これに対し、ParseExact メソッドでは、成功する可能性が高い 1 つ以上の正確な解析パターンを明示的に指定する必要があります。 詳細については、DateTimeFormatInfo トピックの「DateTimeFormatInfo と動的データ」セクションを参照してください。

大事な

特定のカルチャの書式設定規則は動的であり、変更される可能性があることに注意してください。 つまり、既定の (現在の) カルチャの書式設定規則に依存する解析操作や、インバリアント カルチャ以外のカルチャを表す IFormatProvider オブジェクトを指定する解析操作は、次のいずれかが発生した場合に予期せず失敗する可能性があります。

  • カルチャ固有のデータは、.NET Framework のメジャー バージョンまたはマイナー バージョン間で、または .NET Framework の既存のバージョンへの更新の結果として変更されました。
  • カルチャ固有のデータにはユーザー設定が反映されます。ユーザー設定は、コンピューターやセッションごとに異なる場合があります。
  • カルチャ固有のデータは、標準カルチャまたはカスタム カルチャの設定をオーバーライドする代替カルチャを表します。

カルチャ データの変更に関連するデータ文字列と時刻文字列の解析が困難にならないように、インバリアント カルチャを使用して日付と時刻の文字列を解析するか、ParseExact または TryParseExact メソッドを呼び出して、解析する文字列の正確な形式を指定できます。 日付と時刻のデータをシリアル化および逆シリアル化する場合は、インバリアント カルチャの書式設定規則を使用するか、バイナリ形式で DateTime 値をシリアル化および逆シリアル化できます。

詳細については、CultureInfo トピックの「動的カルチャ データ」セクションと、DateTime トピックの「DateTime 値の永続化」セクションを参照してください。

要素の解析とスタイル設定

すべての Parse オーバーロードは、入力文字列の先頭、内側、または末尾の空白文字を無視します (次の表の s で表されます)。 日付と時刻は、先頭と末尾の NUMBER SIGN 文字 ("#"、U+0023) のペアで角かっこで囲み、1 つ以上の NULL 文字 (U+0000) で後ろに続けることができます。

さらに、Parse(String, IFormatProvider, DateTimeStyles) オーバーロードには、DateTimeStyles 列挙体の 1 つ以上のメンバーで構成される styles パラメーターがあります。 このパラメーターは、s の解釈方法と、解析操作で s を日付と時刻に変換する方法を定義します。 次の表では、各 DateTimeStyles メンバーが解析操作に及ぼす影響について説明します。

DateTimeStyles メンバー 変換への影響
AdjustToUniversal s を解析し、必要に応じて、次のように UTC に変換します。

- s にタイム ゾーン オフセットが含まれている場合、または s にタイム ゾーン情報が含まれているが、AssumeLocal フラグが含まれている styles 場合、メソッドは文字列を解析し、ToUniversalTime を呼び出して返された DateTime 値を UTC に変換し、Kind プロパティを DateTimeKind.Utcに設定します。
- s が UTC を表していることを示す場合、または s にタイム ゾーン情報が含まれていないが、AssumeUniversal フラグが含まれている styles 場合、メソッドは文字列を解析し、返された DateTime 値に対してタイム ゾーン変換を実行せず、Kind プロパティを DateTimeKind.Utcに設定します。
- それ以外の場合は、フラグは無効です。
AllowInnerWhite この値は無視されます。 内側の空白は、常に sの日付と時刻の要素で許可されます。
AllowLeadingWhite この値は無視されます。 先頭の空白は、常に sの日付と時刻の要素で許可されます。
AllowTrailingWhite この値は無視されます。 末尾の空白は、常に sの日付と時刻の要素で許可されます。
AllowWhiteSpaces s に先頭、内側、および末尾の空白を含めることができます。 これが既定の動作です。 Noneなど、より制限の厳しい DateTimeStyles 列挙値を指定してオーバーライドすることはできません。
AssumeLocal s にタイム ゾーン情報がない場合は、現地時刻を想定することを指定します。 AdjustToUniversal フラグが存在しない限り、返される DateTime 値の Kind プロパティは DateTimeKind.Localに設定されます。
AssumeUniversal s にタイム ゾーン情報がない場合、UTC と見なされることを指定します。 AdjustToUniversal フラグが存在しない限り、メソッドは返された DateTime 値を UTC から現地時刻に変換し、Kind プロパティを DateTimeKind.Localに設定します。
None 有効ですが、この値は無視されます。
RoundtripKind タイム ゾーン情報を含む文字列の場合は、Kind プロパティが DateTimeKind.Localに設定されたローカル時刻を表す DateTime 値への日付と時刻の文字列の変換を防ぎます。 通常、このような文字列は、DateTime.ToString(String) メソッドを呼び出し、"o"、"r"、または "u" 標準書式指定子を使用して作成されます。

戻り値と DateTime.Kind

DateTime.Parse オーバーロードは、Kind プロパティにタイム ゾーン情報が含まれる DateTime 値を返します。 これは、時刻が次の場合であることを示すことができます。

一般に、Parse メソッドは、Kind プロパティが DateTimeKind.UnspecifiedDateTime オブジェクトを返します。 ただし、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 フラグが、"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 に変換します。

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
String

変換する日付と時刻を含む文字列。 詳細については、「 を解析する文字列」を参照してください。

戻り値

sに含まれる日付と時刻に相当するオブジェクト。

例外

snullです。

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 にタイム ゾーン情報が含まれている場合、このメソッドは、Kind プロパティが DateTimeKind.LocalDateTime 値を返し、s の日付と時刻を現地時刻に変換します。 それ以外の場合は、タイム ゾーン変換を実行せず、Kind プロパティが DateTimeKind.UnspecifiedDateTime 値を返します。

このオーバーロードは、現在のカルチャの書式設定規則を使用して、s の解析を試みます。 現在のカルチャは、CurrentCulture プロパティによって示されます。 特定のカルチャの書式設定規則を使用して文字列を解析するには、Parse(String, IFormatProvider) または Parse(String, IFormatProvider, DateTimeStyles) オーバーロードを呼び出します。

このオーバーロードは、DateTimeStyles.AllowWhiteSpaces スタイルを使用して s の解析を試みます。

こちらもご覧ください

  • TryParse
  • CultureInfo
  • DateTimeFormatInfo
  • .NET Framework での日付と時刻の文字列の解析の
  • 標準の日時書式指定文字列 を する
  • カスタム日時書式指定文字列 を する

適用対象

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

パラメーター

s
String

変換する日付と時刻を含む文字列。 詳細については、「 を解析する文字列」を参照してください。

provider
IFormatProvider

sに関するカルチャ固有の書式情報を提供するオブジェクト。 解析と文化の規則に関する を参照してください

戻り値

providerで指定された s に含まれる日付と時刻に相当するオブジェクト。

実装

例外

snullです。

s には、日付と時刻の有効な文字列表現が含まれていません。

次の例では、en-US、fr-FR、および de-DE カルチャの規則を使用して、日付文字列の配列を解析します。 これは、1 つの日付の文字列表現を異なるカルチャ間で異なる方法で解釈できることを示しています。

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 にタイム ゾーン情報が含まれている場合、このメソッドは、Kind プロパティが DateTimeKind.LocalDateTime 値を返し、s の日付と時刻を現地時刻に変換します。 それ以外の場合は、タイム ゾーン変換を実行せず、Kind プロパティが DateTimeKind.UnspecifiedDateTime 値を返します。

このオーバーロードは、DateTimeStyles.AllowWhiteSpaces スタイルを使用して s の解析を試みます。

こちらもご覧ください

  • TryParse
  • CultureInfo
  • DateTimeFormatInfo
  • .NET Framework での日付と時刻の文字列の解析の
  • 標準の日時書式指定文字列 を する
  • カスタム日時書式指定文字列 を する

適用対象

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です。

戻り値

provider および stylesで指定された、sに含まれる日付と時刻に相当するオブジェクト。

例外

s には、日付と時刻の有効な文字列表現が含まれていません。

styles には、DateTimeStyles 値の無効な組み合わせが含まれています。 たとえば、AssumeLocalAssumeUniversalの両方です。

適用対象

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

パラメーター

s
String

変換する日付と時刻を含む文字列。 詳細については、「 を解析する文字列」を参照してください。

provider
IFormatProvider

sに関するカルチャ固有の書式設定情報を提供するオブジェクト。 解析と文化の規則に関する を参照してください

styles
DateTimeStyles

解析操作を成功させるために s に存在できるスタイル要素を示し、現在のタイム ゾーンまたは現在の日付に関連して解析された日付を解釈する方法を定義する列挙値のビットごとの組み合わせ。 指定する一般的な値は Noneです。

戻り値

provider および stylesで指定された、sに含まれる日付と時刻に相当するオブジェクト。

例外

snullです。

s には、日付と時刻の有効な文字列表現が含まれていません。

styles には、DateTimeStyles 値の無効な組み合わせが含まれています。 たとえば、AssumeLocalAssumeUniversalの両方です。

次の例では、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

こちらもご覧ください

適用対象