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) です。 これは、DateTimeDateTimeOffsetTimeZoneInfo 型とそのメンバーについて説明する例の、動作と出力に影響を与える可能性があります。

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

注釈

このセクションの内容:

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

終了 Call (英語の可能性あり)
現在のカルチャの規則を使用して、日付と時刻の文字列を解析します。 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 せずに、入力文字列を完全に解析しようとします。

重要

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

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

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

  • 日付を含むが、時刻コンポーネントを含まない文字列。 時刻コンポーネントが存在しない場合、メソッドは午前 0 時 12 分を想定します。 日付コンポーネントに 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 使用し、書式指定子を指定します。

解析とカルチャの規則

解析される Parse 文字列 (次の表で表 s す) が ISO 8601 パターンに準拠していない限り、メソッドのすべてのオーバーロードはカルチャに依存します。 解析操作では、次のように派生したオブジェクトの DateTimeFormatInfo 書式設定情報が使用されます。

重要

和暦の時代 (年号) は天皇の代に基づいているため、変更されることが予想されます。 たとえば、JapaneseCalendarJapaneseLunisolarCalendar において、2019 年 5 月 1 日から令和時代が始まることになりました。 このような時代 (年号) の変更は、これらのカレンダーを使用するすべてのアプリケーションに影響します。 詳細と、アプリケーションが影響を受けるかどうかを判断するには、「 .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に更新された結果として変更されています。
  • カルチャ固有のデータにはユーザー設定が反映されます。ユーザー設定は、コンピューターやセッションごとに異なる場合があります。
  • カルチャ固有のデータは、標準カルチャまたはカスタム カルチャの設定をオーバーライドする置換カルチャを表します。

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

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

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

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

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

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

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

戻り値と DateTime.Kind

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

一般に、 メソッドは Parse プロパティDateTimeKind.Unspecifiedが である DateTime オブジェクトをKind返します。 ただし、 メソッドはParse、 パラメーターと styles パラメーターの値に応じて、タイム ゾーン変換をKind実行し、 プロパティのs値を異なる方法で設定することもできます。

If タイム ゾーン変換 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値を保持することもできます。 次の例は、"o"、"r"、または "u" 書式指定子を使用して文字列に変換される値に対DateTimeする解析操作にフラグがどのように影響するかをRoundtripKind示しています。

   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 の文字列表現を同等の形式に変換します。

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

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

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

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Char>, IFormatProvider)

文字のスパンを値に解析します。

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 に変換します。

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 に関するカルチャ固有の書式情報を提供するオブジェクト。 「解析およびカルチャの規則」をご覧ください。

戻り値

s で指定された書式に従って表記された、provider に含まれる日時と等価のオブジェクト。

実装

例外

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

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

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

カルチャ固有の書式情報と書式スタイルを使用して、日付と時刻の文字列形式を含むメモリ範囲を等価の 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 に日付と時刻の有効な文字列形式が含まれていません。

stylesDateTimeStyles 値の正しくない組み合わせが含まれています。 たとえば、AssumeLocalAssumeUniversal の両方です。

適用対象

Parse(String, IFormatProvider, DateTimeStyles)

カルチャ固有の書式情報と書式スタイルを使用して、日付と時刻の文字列形式を等価の 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 に日付と時刻の有効な文字列形式が含まれていません。

stylesDateTimeStyles 値の正しくない組み合わせが含まれています。 たとえば、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.

注釈

このメソッドオーバーロードは、 の日付と時刻 sKind 変換し、戻り DateTime 値の プロパティを次のように設定します。

If タイム ゾーン変換 Kind プロパティ
s にはタイム ゾーン情報が含まれない。 [なし] : DateTimeKind.Unspecified
s にはタイム ゾーン情報が含まれています。 ローカル タイム ゾーンの時刻へ DateTimeKind.Local
s にはタイム ゾーン情報が含まれており styles 、 には フラグが DateTimeStyles.AdjustToUniversal 含まれます。 協定世界時 (UTC) へ DateTimeKind.Utc
s には Z または GMT タイム ゾーン指定子が含まれており styles 、 には が DateTimeStyles.RoundtripKind含まれます。 [なし] : DateTimeKind.Utc

こちらもご覧ください

適用対象