DateTimeOffset.ParseExact メソッド

定義

指定した文字列形式の日付と時刻を等価の DateTimeOffset の値に変換します。 文字列形式の書式は、指定した書式と完全に一致する必要があります。

オーバーロード

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

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、指定した日付と時刻の文字列形式を等価の DateTimeOffset に変換します。 文字列形式の書式は、指定されたいずれかの書式と完全に一致する必要があります。

ParseExact(String, String, IFormatProvider, DateTimeStyles)

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、指定した日付と時刻の文字列形式を等価の DateTimeOffset に変換します。 文字列形式の書式は、指定した書式と完全に一致する必要があります。

ParseExact(String, String, IFormatProvider)

指定した書式とカルチャ固有の書式情報を使用して、指定した日付と時刻の文字列形式を等価の DateTimeOffset の値に変換します。 文字列形式の書式は、指定した書式と完全に一致する必要があります。

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

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、日付と時刻を表す文字範囲を等価の DateTimeOffset に変換します。 日付と時刻を表すための書式は、指定した書式と完全に一致する必要があります。

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

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、日付と時刻の文字列表現を含む文字範囲を等価の DateTimeOffset に変換します。 日付と時刻を表すための書式は、指定した書式のいずれかと完全に一致する必要があります。

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

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、指定した日付と時刻の文字列形式を等価の DateTimeOffset に変換します。 文字列形式の書式は、指定されたいずれかの書式と完全に一致する必要があります。

public:
 static DateTimeOffset ParseExact(System::String ^ input, cli::array <System::String ^> ^ formats, IFormatProvider ^ formatProvider, System::Globalization::DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string[] formats, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string[] formats, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles);
static member ParseExact : string * string[] * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As String, formats As String(), formatProvider As IFormatProvider, styles As DateTimeStyles) As DateTimeOffset

パラメーター

input
String

変換する日時を含む文字列。

formats
String[]

input の有効な書式を定義する書式指定子の配列。

formatProvider
IFormatProvider

input に関するカルチャ固有の書式情報を提供するオブジェクト。

styles
DateTimeStyles

input で使用可能な書式を示す、列挙値のビットごとの組み合わせ。

戻り値

DateTimeOffset

formatsformatProvider、および styles の各パラメーターで指定された書式に従って表記された、input パラメーターに含まれる日時と等価のオブジェクト。

例外

オフセットが -14 時間より小さいか、14 時間を超えています。

  • または -

サポートされていない値が styles に含まれています。

  • または -

同時に使用できない DateTimeStyles 値が styles パラメーターに含まれています。

inputnullです。

input が空の文字列 ("") です。

  • または -

input に日付と時刻の有効な文字列形式が含まれていません。

  • または -

formats の要素に有効な書式指定子が含まれていません。

  • または -

input の時間の部分と AM/PM 指定子が一致していません。

次の例では、日付と時刻とオフセット値の文字列表現に対して複数の入力形式を定義し、ユーザーが入力した文字列をメソッドに DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 渡します。

TextReader conIn = Console.In;
TextWriter conOut = Console.Out;
int tries = 0;
string input = String.Empty;
string[] formats = new string[] {@"@M/dd/yyyy HH:m zzz", @"MM/dd/yyyy HH:m zzz",
                                 @"M/d/yyyy HH:m zzz", @"MM/d/yyyy HH:m zzz",
                                 @"M/dd/yy HH:m zzz", @"MM/dd/yy HH:m zzz",
                                 @"M/d/yy HH:m zzz", @"MM/d/yy HH:m zzz",
                                 @"M/dd/yyyy H:m zzz", @"MM/dd/yyyy H:m zzz",
                                 @"M/d/yyyy H:m zzz", @"MM/d/yyyy H:m zzz",
                                 @"M/dd/yy H:m zzz", @"MM/dd/yy H:m zzz",
                                 @"M/d/yy H:m zzz", @"MM/d/yy H:m zzz",
                                 @"M/dd/yyyy HH:mm zzz", @"MM/dd/yyyy HH:mm zzz",
                                 @"M/d/yyyy HH:mm zzz", @"MM/d/yyyy HH:mm zzz",
                                 @"M/dd/yy HH:mm zzz", @"MM/dd/yy HH:mm zzz",
                                 @"M/d/yy HH:mm zzz", @"MM/d/yy HH:mm zzz",
                                 @"M/dd/yyyy H:mm zzz", @"MM/dd/yyyy H:mm zzz",
                                 @"M/d/yyyy H:mm zzz", @"MM/d/yyyy H:mm zzz",
                                 @"M/dd/yy H:mm zzz", @"MM/dd/yy H:mm zzz",
                                 @"M/d/yy H:mm zzz", @"MM/d/yy H:mm zzz"};
IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat;
DateTimeOffset result = new DateTimeOffset();

do {
   conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),");
   conOut.Write("Then press Enter: ");
   input = conIn.ReadLine();
   conOut.WriteLine();
   try
   {
      result = DateTimeOffset.ParseExact(input, formats, provider,
                                         DateTimeStyles.AllowWhiteSpaces);
      break;
   }
   catch (FormatException)
   {
      Console.WriteLine("Unable to parse {0}.", input);
      tries++;
   }
} while (tries < 3);
if (tries >= 3)
   Console.WriteLine("Exiting application without parsing {0}", input);
else
   Console.WriteLine("{0} was converted to {1}", input, result.ToString());
// Some successful sample interactions with the user might appear as follows:
//    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
//    Then press Enter: 12/08/2007 6:54 -6:00
//
//    12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00
//
//    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
//    Then press Enter: 12/8/2007 06:54 -06:00
//
//    12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00
//
//    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
//    Then press Enter: 12/5/07 6:54 -6:00
//
//    12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00
let input = String.Empty
let formats = 
    [| @"@M/dd/yyyy HH:m zzz"; @"MM/dd/yyyy HH:m zzz";
       @"M/d/yyyy HH:m zzz"; @"MM/d/yyyy HH:m zzz"
       @"M/dd/yy HH:m zzz"; @"MM/dd/yy HH:m zzz"
       @"M/d/yy HH:m zzz"; @"MM/d/yy HH:m zzz"
       @"M/dd/yyyy H:m zzz"; @"MM/dd/yyyy H:m zzz"
       @"M/d/yyyy H:m zzz"; @"MM/d/yyyy H:m zzz"
       @"M/dd/yy H:m zzz"; @"MM/dd/yy H:m zzz"
       @"M/d/yy H:m zzz"; @"MM/d/yy H:m zzz"
       @"M/dd/yyyy HH:mm zzz"; @"MM/dd/yyyy HH:mm zzz"
       @"M/d/yyyy HH:mm zzz"; @"MM/d/yyyy HH:mm zzz"
       @"M/dd/yy HH:mm zzz"; @"MM/dd/yy HH:mm zzz"
       @"M/d/yy HH:mm zzz"; @"MM/d/yy HH:mm zzz"
       @"M/dd/yyyy H:mm zzz"; @"MM/dd/yyyy H:mm zzz"
       @"M/d/yyyy H:mm zzz"; @"MM/d/yyyy H:mm zzz"
       @"M/dd/yy H:mm zzz"; @"MM/dd/yy H:mm zzz"
       @"M/d/yy H:mm zzz"; @"MM/d/yy H:mm zzz" |]
let provider = CultureInfo.InvariantCulture.DateTimeFormat

let mutable result = None
let mutable tries = 0
while tries < 3 && result.IsNone do
    printfn "Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),"
    printf "Then press Enter: "
    let input = stdin.ReadLine()
    printfn ""
    try
        result <- 
            DateTimeOffset.ParseExact(input, formats, provider, DateTimeStyles.AllowWhiteSpaces) 
            |> Some
    with :? FormatException ->
        printfn $"Unable to parse {input}."
        tries <- tries + 1

match result with
| Some result ->
    printfn $"{input} was converted to {result}"
| None ->
    printfn $"Exiting application without parsing {input}"

// Some successful sample interactions with the user might appear as follows:
//    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
//    Then press Enter: 12/08/2007 6:54 -6:00
//
//    12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00
//
//    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
//    Then press Enter: 12/8/2007 06:54 -06:00
//
//    12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00
//
//    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
//    Then press Enter: 12/5/07 6:54 -6:00
//
//    12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00
 Dim conIn As TextReader = Console.In
 Dim conOut As TextWriter = Console.Out
 Dim tries As Integer = 0
 Dim input As String = String.Empty
 Dim formats() As String = {"M/dd/yyyy HH:m zzz", "MM/dd/yyyy HH:m zzz", _
                            "M/d/yyyy HH:m zzz", "MM/d/yyyy HH:m zzz", _
                            "M/dd/yy HH:m zzz", "MM/dd/yy HH:m zzz", _
                            "M/d/yy HH:m zzz", "MM/d/yy HH:m zzz", _                                 
                            "M/dd/yyyy H:m zzz", "MM/dd/yyyy H:m zzz", _
                            "M/d/yyyy H:m zzz", "MM/d/yyyy H:m zzz", _
                            "M/dd/yy H:m zzz", "MM/dd/yy H:m zzz", _
                            "M/d/yy H:m zzz", "MM/d/yy H:m zzz", _                               
                            "M/dd/yyyy HH:mm zzz", "MM/dd/yyyy HH:mm zzz", _
                            "M/d/yyyy HH:mm zzz", "MM/d/yyyy HH:mm zzz", _
                            "M/dd/yy HH:mm zzz", "MM/dd/yy HH:mm zzz", _
                            "M/d/yy HH:mm zzz", "MM/d/yy HH:mm zzz", _                                 
                            "M/dd/yyyy H:mm zzz", "MM/dd/yyyy H:mm zzz", _
                            "M/d/yyyy H:mm zzz", "MM/d/yyyy H:mm zzz", _
                            "M/dd/yy H:mm zzz", "MM/dd/yy H:mm zzz", _
                            "M/d/yy H:mm zzz", "MM/d/yy H:mm zzz"}   
 Dim provider As IFormatProvider = CultureInfo.InvariantCulture.DateTimeFormat
 Dim result As DateTimeOffset

 Do 
    conOut.WriteLine("Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),")
    conOut.Write("Then press Enter: ")
    input = conIn.ReadLine()
    conOut.WriteLine() 
    Try
       result = DateTimeOffset.ParseExact(input, formats, provider, _
                                          DateTimeStyles.AllowWhiteSpaces)
       Exit Do
    Catch e As FormatException
       Console.WriteLine("Unable to parse {0}.", input)      
       tries += 1
    End Try
 Loop While tries < 3
 If tries >= 3 Then
    Console.WriteLine("Exiting application without parsing {0}", input)
 Else
    Console.WriteLine("{0} was converted to {1}", input, result.ToString())                                                     
 End If 
 ' Some successful sample interactions with the user might appear as follows:
 '    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 '    Then press Enter: 12/08/2007 6:54 -6:00
 '    
 '    12/08/2007 6:54 -6:00 was converted to 12/8/2007 6:54:00 AM -06:00         
 '    
 '    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 '    Then press Enter: 12/8/2007 06:54 -06:00
 '    
 '    12/8/2007 06:54 -06:00 was converted to 12/8/2007 6:54:00 AM -06:00
 '    
 '    Enter a date, time, and offset (MM/DD/YYYY HH:MM +/-HH:MM),
 '    Then press Enter: 12/5/07 6:54 -6:00
 '    
 '    12/5/07 6:54 -6:00 was converted to 12/5/2007 6:54:00 AM -06:00

注釈

このメソッドは DateTimeOffset.ParseExact(String, String[], IFormatProvider, DateTimeStyles) 、パラメーターに割り当てられたパターンのいずれかに一致する日付の文字列表現を formats 解析します。 文字列が input パラメーターによって styles 定義されたバリエーションのいずれかとこれらのパターンのいずれとも一致しない場合、このメソッド FormatExceptionは .. 複数の書式設定パターンと比較する input 以外に、このオーバーロードはメソッドと同じように DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles) 動作します。

パラメーターは formats 、要素に 1 つの標準書式指定子またはパラメーターの使用可能なパターンを定義する 1 つ以上の input カスタム書式指定子を含む文字列配列です。 メソッドが呼び出されると、 input これらのパターンのいずれかに一致する必要があります。 有効な書式設定コードの詳細については、「 標準の日付と時刻の書式指定文字列 」および 「カスタム日時書式指定文字列」を参照してください。 一致する要素にformats、オフセットが存在inputする必要があることを示す 、zzまたはzzzカスタム書式指定子が含まれているz場合、そのオフセットには負符号または正符号を含める必要があります。 符号が見つからない場合、メソッド FormatExceptionは .

重要

このオーバーロードのパラメーターを formats 使用して複数の形式を指定すると、多くのユーザーが日付と時刻を入力するときの不満を軽減できます。 特に、複数の入力パターンを定義する機能により、アプリケーションは、月、日、時間、分、秒で先行ゼロを含めたり欠けたりする日付と時刻の表現を処理できます。 この例では、この図を示します。

一致した要素に formats 日付が含まれているが input 時刻が含まれていない必要がある場合、結果の DateTimeOffset オブジェクトには午前 0 時 (0:00:00) の時刻が割り当てられます。 一致する要素に formats 日付ではなく時刻が含まれている input 必要がある場合、結果 DateTimeOffset のオブジェクトにはローカル システムの現在の日付が割り当てられます。 一致した要素に formats オフセットを含む input 必要がない場合、結果 DateTimeOffset のオブジェクトのオフセットはパラメーターの styles 値によって異なります。 含まれているAssumeLocal場合styles、ローカル タイム ゾーンのオフセットがオブジェクトにDateTimeOffset割り当てられます。 含まれているAssumeUniversal場合stylesは、協定世界時 (UTC) オフセット (+00:00) がオブジェクトにDateTimeOffset割り当てられます。 どちらの値も指定しない場合は、ローカル タイム ゾーンのオフセットが使用されます。

使用される input 特定の日付と時刻のシンボルと文字列は、パラメーターによって formatProvider 定義されます。 一致する要素が標準書式指定子文字列の input場合、正確な形式の formats 場合も同様です。 パラメーターには formatProvider 、次のいずれかを指定できます。

ある場合 formatprovidernull、現在の CultureInfo カルチャに対応するオブジェクトが使用されます。

このパラメーターは styles 、入力文字列で空白を許可するかどうかを定義し、明示的なオフセット コンポーネントのない文字列の解析方法を示し、解析操作の一環として UTC 変換をサポートします。 列挙体のすべてのメンバーが DateTimeStyles サポートされています。ただし、次を除きます NoCurrentDateDefault。 次の表に、サポートされている各メンバーの効果を示します。

DateTimeStyles のメンバー 動作
AdjustToUniversal input解析し、必要に応じて UTC に変換します。 これは、文字列を解析してから、返されたDateTimeOffsetオブジェクトのメソッドをDateTimeOffset.ToUniversalTime呼び出すことと同じです。
AssumeLocal 一致した要素に formats オフセット値を含む input 必要がない場合、返される DateTimeOffset オブジェクトにはローカル タイム ゾーンのオフセットが指定されます。 これが既定値です。
AssumeUniversal 一致した要素に formats オフセット値を含む input 必要がない場合、返される DateTimeOffset オブジェクトには UTC オフセット (+00:00) が与えられます。
AllowInnerWhite で指定formatされていない内側の空白を含めることができますinput。 日付と時刻のコンポーネントの間と個々のコンポーネント (オフセットを除く) 内に余分な空白が表示される可能性があり、文字列の解析時には無視されます。
AllowLeadingWhite で指定されていない先頭のスペースをformats含めることができますinput。 文字列を解析する場合、これらは無視されます。
AllowTrailingWhite で指定されていない末尾のスペースをformats含めることができますinput。 文字列を解析する場合、これらは無視されます。
AllowWhiteSpaces で指定されていない先頭、末尾、および内側のスペースをformats含めることができますinput。 文字列の解析時に、一致する要素 formats で指定されていない余分な空白文字はすべて無視されます。
None で追加の空白が許可されていないことを input示します。 空白は、一致する要素の特定の formats 要素で指定されたとおりに表示する必要があります。 これは既定の動作です。
RoundtripKind 構造体にプロパティが DateTimeOffset 含まれていないため、 Kind 効果はありません。

注意 (呼び出し元)

.NET Framework 4 では、ParseExact解析される文字列に時間コンポーネントと、一致しない AM/PM 指定子が含まれている場合、メソッドは a FormatException をスローします。 .NET Framework 3.5 以前のバージョンでは、AM/PM 指定子は無視されます。

こちらもご覧ください

適用対象

ParseExact(String, String, IFormatProvider, DateTimeStyles)

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、指定した日付と時刻の文字列形式を等価の DateTimeOffset に変換します。 文字列形式の書式は、指定した書式と完全に一致する必要があります。

public:
 static DateTimeOffset ParseExact(System::String ^ input, System::String ^ format, IFormatProvider ^ formatProvider, System::Globalization::DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles);
static member ParseExact : string * string * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As String, format As String, formatProvider As IFormatProvider, styles As DateTimeStyles) As DateTimeOffset

パラメーター

input
String

変換する日時を含む文字列。

format
String

input の有効な書式を定義する書式指定子。

formatProvider
IFormatProvider

input に関するカルチャ固有の書式情報を提供するオブジェクト。

styles
DateTimeStyles

input で使用可能な書式を示す、列挙値のビットごとの組み合わせ。

戻り値

DateTimeOffset

formatformatProvider、および styles の各パラメーターで指定された書式に従って表記された、input パラメーターに含まれる日時と等価のオブジェクト。

例外

オフセットが -14 時間より小さいか、14 時間を超えています。

  • または -

サポートされていない値が styles パラメーターに含まれています。

  • または -

同時に使用できない DateTimeStyles 値が styles パラメーターに含まれています。

inputnullです。

または

formatnullです。

input が空の文字列 ("") です。

  • または -

input に日付と時刻の有効な文字列形式が含まれていません。

  • または -

format が空の文字列です。

または

input の時間の部分と AM/PM 指定子が一致していません。

次の例では、 DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles) 標準書式指定子とカスタム書式指定子、インバリアント カルチャ、およびさまざまな DateTimeStyles 値を持つメソッドを使用して、いくつかの日付と時刻の文字列を解析します。

string dateString, format;
DateTimeOffset result;
CultureInfo provider = CultureInfo.InvariantCulture;

// Parse date-only value with invariant culture and assume time is UTC.
dateString = "06/15/2008";
format = "d";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider,
                                      DateTimeStyles.AssumeUniversal);
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("'{0}' is not in the correct format.", dateString);
}

// Parse date-only value with leading white space.
// Should throw a FormatException because only trailing white space is
// specified in method call.
dateString = " 06/15/2008";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider,
                                      DateTimeStyles.AllowTrailingWhite);
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("'{0}' is not in the correct format.", dateString);
}

// Parse date and time value, and allow all white space.
dateString = " 06/15/   2008  15:15    -05:00";
format = "MM/dd/yyyy H:mm zzz";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider,
                                      DateTimeStyles.AllowWhiteSpaces);
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("'{0}' is not in the correct format.", dateString);
}

// Parse date and time and convert to UTC.
dateString = "  06/15/2008 15:15:30 -05:00";
format = "MM/dd/yyyy H:mm:ss zzz";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider,
                                      DateTimeStyles.AllowWhiteSpaces |
                                      DateTimeStyles.AdjustToUniversal);
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("'{0}' is not in the correct format.", dateString);
}
// The example displays the following output:
//    '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00.
//    ' 06/15/2008' is not in the correct format.
//    ' 06/15/   2008  15:15    -05:00' converts to 6/15/2008 3:15:00 PM -05:00.
//    '  06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00.
let provider = CultureInfo.InvariantCulture

// Parse date-only value with invariant culture and assume time is UTC.
let dateString = "06/15/2008"
let format = "d"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider, DateTimeStyles.AssumeUniversal)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// Parse date-only value with leading white space.
// Should throw a FormatException because only trailing white space is
// specified in method call.
let dateString = " 06/15/2008"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider, DateTimeStyles.AllowTrailingWhite)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// Parse date and time value, and allow all white space.
let dateString = " 06/15/   2008  15:15    -05:00"
let format = "MM/dd/yyyy H:mm zzz"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider, DateTimeStyles.AllowWhiteSpaces)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// Parse date and time and convert to UTC.
let dateString = "  06/15/2008 15:15:30 -05:00"
let format = "MM/dd/yyyy H:mm:ss zzz"
try
    let result = 
        DateTimeOffset.ParseExact(dateString, format, provider,
                                  DateTimeStyles.AllowWhiteSpaces |||
                                  DateTimeStyles.AdjustToUniversal)
    printfn $"'{dateString}' converts to {result}."
with :? FormatException ->
    printfn $"'{dateString}' is not in the correct format."

// The example displays the following output:
//    '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00.
//    ' 06/15/2008' is not in the correct format.
//    ' 06/15/   2008  15:15    -05:00' converts to 6/15/2008 3:15:00 PM -05:00.
//    '  06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00.
Dim dateString, format As String  
Dim result As DateTimeOffset
Dim provider As CultureInfo = CultureInfo.InvariantCulture

' Parse date-only value with invariant culture and assume time is UTC.
dateString = "06/15/2008"
format = "d"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AssumeUniversal)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 

' Parse date-only value with leading white space.
' Should throw a FormatException because only trailing white space is  
' specified in method call.
dateString = " 06/15/2008"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AllowTrailingWhite)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 

' Parse date and time value, and allow all white space.
dateString = " 06/15/   2008  15:15    -05:00"
format = "MM/dd/yyyy H:mm zzz"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AllowWhiteSpaces)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 

' Parse date and time and convert to UTC.
dateString = "  06/15/2008 15:15:30 -05:00"   
format = "MM/dd/yyyy H:mm:ss zzz"       
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider, _
                                      DateTimeStyles.AllowWhiteSpaces Or _
                                      DateTimeStyles.AdjustToUniversal)
   Console.WriteLine("'{0}' converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("'{0}' is not in the correct format.", dateString)
End Try 
' The example displays the following output:
'    '06/15/2008' converts to 6/15/2008 12:00:00 AM +00:00.
'    ' 06/15/2008' is not in the correct format.
'    ' 06/15/   2008  15:15    -05:00' converts to 6/15/2008 3:15:00 PM -05:00.
'    '  06/15/2008 15:15:30 -05:00' converts to 6/15/2008 8:15:30 PM +00:00.

次の DateTimeStyles 例では、さまざまな値を使用して、 ISO 8601 に準拠すると予想される文字列の配列を解析します。 この例の出力に示すように、適切な形式の文字列は、次の場合に解析に失敗します。

  • 空白と適切な DateTimeStyles フラグ (メソッド呼び出しで指定されていないなど DateTimeStyles.AllowWhiteSpaces ) が含まれています。

  • には、範囲外の日付と時刻の要素が含まれています。

UTC オフセットを指定しない文字列は、メソッド呼び出しでフラグが指定されていない限り DateTimeStyles.AssumeUniversal 、ローカル タイム ゾーン (この場合は -07:00) のオフセットを持つものと見なされます。 その場合、それらは世界協定時刻と見なされます。

module parseexact_iso8601_2

open System
open System.Globalization

let dateStrings = 
    [| "2018-08-18T12:45:16.0000000Z"
       "2018/08/18T12:45:16.0000000Z"
       "2018-18-08T12:45:16.0000000Z"
       "2018-08-18T12:45:16.0000000"                               
       " 2018-08-18T12:45:16.0000000Z "
       "2018-08-18T12:45:16.0000000+02:00"
       "2018-08-18T12:45:16.0000000-07:00" |] 

let parseWithISO8601 dateStrings styles =
    printfn $"Parsing with {styles}:"
    for dateString in dateStrings do
        try
            let date = DateTimeOffset.ParseExact(dateString, "O", null, styles)
            printfn $"""   {dateString,-35} --> {date.ToString "yyyy-MM-dd HH:mm:ss.FF zzz"}"""
        with :? FormatException ->
            printfn $"   FormatException: Unable to convert '{dateString}'"

parseWithISO8601 dateStrings DateTimeStyles.None
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AllowWhiteSpaces
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AdjustToUniversal
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AssumeLocal
printfn "\n-----\n"
parseWithISO8601 dateStrings DateTimeStyles.AssumeUniversal


// The example displays the following output:
//      Parsing with None:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AllowWhiteSpaces:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         2018-08-18T12:45:16.0000000Z       --> 2018-08-18 12:45:16 +00:00
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AdjustToUniversal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 19:45:16 +00:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 10:45:16 +00:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 19:45:16 +00:00
//
//      -----
//
//      Parsing with AssumeLocal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AssumeUniversal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = { "2018-08-18T12:45:16.0000000Z",
                               "2018/08/18T12:45:16.0000000Z",
                               "2018-18-08T12:45:16.0000000Z",
                               "2018-08-18T12:45:16.0000000",                               
                               " 2018-08-18T12:45:16.0000000Z ",
                               "2018-08-18T12:45:16.0000000+02:00",
                               "2018-08-18T12:45:16.0000000-07:00" }; 
      
      ParseWithISO8601(dateStrings, DateTimeStyles.None);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal);
      Console.WriteLine("\n-----\n");
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal);   }

   private static void ParseWithISO8601(string[] dateStrings, DateTimeStyles styles)
   {   
      Console.WriteLine($"Parsing with {styles}:");
      foreach (var dateString in dateStrings)
      {
         try {
            var date = DateTimeOffset.ParseExact(dateString, "O", null, styles);
            Console.WriteLine($"   {dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}");
         }
         catch (FormatException)
         {
            Console.WriteLine($"   FormatException: Unable to convert '{dateString}'");
         }   
      } 
   }
}
// The example displays the following output:
//      Parsing with None:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AllowWhiteSpaces:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         2018-08-18T12:45:16.0000000Z       --> 2018-08-18 12:45:16 +00:00
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AdjustToUniversal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 19:45:16 +00:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 10:45:16 +00:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 19:45:16 +00:00
//
//      -----
//
//      Parsing with AssumeLocal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 -07:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
//
//      -----
//
//      Parsing with AssumeUniversal:
//         2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//         FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//         2018-08-18T12:45:16.0000000         --> 2018-08-18 12:45:16 +00:00
//         FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//         2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//         2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
Imports System.Globalization

Public Module Example
   Public Sub Main()
      Dim dateStrings() = { "2018-08-18T12:45:16.0000000Z",
                            "2018/08/18T12:45:16.0000000Z",
                            "2018-18-08T12:45:16.0000000Z",
                            "2018-08-18T12:45:16.0000000",                               
                            " 2018-08-18T12:45:16.0000000Z ",
                            "2018-08-18T12:45:16.0000000+02:00",
                            "2018-08-18T12:45:16.0000000-07:00" } 
      
      ParseWithISO8601(dateStrings, DateTimeStyles.None)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AllowWhiteSpaces)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AdjustToUniversal)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeLocal)
      Console.WriteLine($"{vbCrLf}-----{vbCrLf}")
      ParseWithISO8601(dateStrings, DateTimeStyles.AssumeUniversal)   
   End Sub

   Private Sub ParseWithISO8601(dateStrings() As String, styles As DateTimeStyles)
      Console.WriteLine($"Parsing with {styles}:")
      For Each dateStr In dateStrings
         Try 
            Dim dat = DateTimeOffset.ParseExact(dateString, "O", Nothing, styles)
            Console.WriteLine($"   {dateString,-35} --> {dat:yyyy-MM-dd HH:mm:ss.FF zzz}")
         catch e As FormatException
            Console.WriteLine($"   FormatException: Unable to convert '{dateString}'")
         End Try   
      Next 
   End Sub
End Module
' The example displays the following output:
'      Parsing with None:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AllowWhiteSpaces:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AdjustToUniversal:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AssumeLocal:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'
'      -----
'
'      Parsing with AssumeUniversal:
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'
'         FormatException: Unable to convert '07-30-2018'

注釈

このメソッドは DateTimeOffset.ParseExact(String, String, IFormatProvider, DateTimeStyles) 、日付の文字列表現を解析します。この形式は、パラメーターで定義された format 形式である必要があります。 また、日付と時刻の<Date>文字列形式の 、<Time>および要素が指定されたformat順序で表示される必要<Offset>があります。 文字列が input パラメーターの format パターンと一致しない場合、パラメーターによって定義された styles バリエーションがある場合、メソッド FormatExceptionは . これに対し、このメソッドは DateTimeOffset.Parse(String, IFormatProvider, DateTimeStyles) 、書式プロバイダー DateTimeFormatInfo のオブジェクトによって認識される形式のいずれかで、日付の文字列表現を解析します。 Parseまた、日付と<Offset>時刻の<Date>文字列表現の 、<Time>要素を任意の順序で表示することもできます。

パラメーターは format 、1 つの標準書式指定子またはパラメーターの必須パターンを定義する 1 つ以上の input カスタム書式指定子を含む文字列です。 有効な書式設定コードの詳細については、「 標準の日付と時刻の書式指定文字列 」および 「カスタム日時書式指定文字列」を参照してください。 オフセットがz存在する必要があることを示す 、zzまたはzzzカスタム書式指定子が含まれている場合formatは、そのオフセットにinput負符号または正符号を含める必要があります。 符号が見つからない場合、メソッド FormatExceptionは .

日付を含むinputが時刻を含まない必要がある場合format、結果DateTimeOffsetのオブジェクトには午前 0 時 (0:00:00) の時刻が割り当てられます。 日付ではなく時刻を含むinput必要がある場合format、結果DateTimeOffsetのオブジェクトにはローカル システムの現在の日付が割り当てられます。 オフセットを含むinput必要がない場合format、結果DateTimeOffsetのオブジェクトのオフセットはパラメーターのstyles値によって異なります。 含まれているAssumeLocal場合styles、ローカル タイム ゾーンのオフセットがオブジェクトにDateTimeOffset割り当てられます。 含まれているAssumeUniversal場合stylesは、協定世界時 (UTC) オフセット (+00:00) がオブジェクトにDateTimeOffset割り当てられます。 どちらの値も指定しない場合は、ローカル タイム ゾーンのオフセットが使用されます。

使用される input 特定の日付と時刻のシンボルと文字列は、パラメーターによって formatProvider 定義されます。 標準書式指定子文字列の場合format、正確な書式inputについても同じことが当てはまります。 パラメーターには formatProvider 、次のいずれかを指定できます。

ある場合 formatprovidernull、現在の CultureInfo カルチャに対応するオブジェクトが使用されます。

このパラメーターは styles 、入力文字列で空白を使用できるかどうかを定義し、明示的なオフセット コンポーネントのない文字列の解析方法を示し、解析操作の一環として UTC 変換をサポートします。 列挙体のすべてのメンバーが DateTimeStyles サポートされています。ただし、次を除きます NoCurrentDateDefault。 次の表に、サポートされている各メンバーの効果を示します。

DateTimeStyles のメンバー 動作
AdjustToUniversal input解析し、必要に応じて UTC に変換します。 これは、文字列を解析してから、返されたDateTimeOffsetオブジェクトのメソッドをDateTimeOffset.ToUniversalTime呼び出すことと同じです。
AssumeLocal オフセット値を含むinput必要がない場合format、返されるDateTimeOffsetオブジェクトにはローカル タイム ゾーンのオフセットが指定されます。 これが既定値です。
AssumeUniversal オフセット値を含むinput必要がない場合format、返されるDateTimeOffsetオブジェクトには UTC オフセット (+00:00) が与えられます。
AllowInnerWhite で指定formatされていない内側の空白を含めることができますinput。 日付と時刻のコンポーネント間と個々のコンポーネント内に余分な空白が表示される可能性があり、文字列の解析時には無視されます。
AllowLeadingWhite で指定されていない先頭のスペースをformat含めることができますinput。 文字列を解析する場合、これらは無視されます。
AllowTrailingWhite で指定されていない末尾のスペースをformat含めることができますinput。 文字列を解析する場合、これらは無視されます。
AllowWhiteSpaces で指定されていない先頭、末尾、および内側のスペースをformat含めることができますinput。 文字列を解析するときに、指定 format されていない余分な空白文字はすべて無視されます。
None で追加の空白が許可されていないことを input示します。 空白は、次で指定したとおりに表示 formatする必要があります。 これは既定の動作です。
RoundtripKind 構造体にプロパティが DateTimeOffset 含まれていないため、 Kind 効果はありません。

注意 (呼び出し元)

.NET Framework 4 では、ParseExact解析される文字列に時間コンポーネントと、一致しない AM/PM 指定子が含まれている場合、メソッドは a FormatException をスローします。 .NET Framework 3.5 以前のバージョンでは、AM/PM 指定子は無視されます。

こちらもご覧ください

適用対象

ParseExact(String, String, IFormatProvider)

指定した書式とカルチャ固有の書式情報を使用して、指定した日付と時刻の文字列形式を等価の DateTimeOffset の値に変換します。 文字列形式の書式は、指定した書式と完全に一致する必要があります。

public:
 static DateTimeOffset ParseExact(System::String ^ input, System::String ^ format, IFormatProvider ^ formatProvider);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider formatProvider);
public static DateTimeOffset ParseExact (string input, string format, IFormatProvider? formatProvider);
static member ParseExact : string * string * IFormatProvider -> DateTimeOffset
Public Shared Function ParseExact (input As String, format As String, formatProvider As IFormatProvider) As DateTimeOffset

パラメーター

input
String

変換する日時を含む文字列。

format
String

input の有効な書式を定義する書式指定子。

formatProvider
IFormatProvider

input に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

DateTimeOffset

formatformatProvider で指定された input に格納される日時と等価のオブジェクト。

例外

オフセットが -14 時間より小さいか、14 時間を超えています。

inputnullです。

または

formatnullです。

input が空の文字列 ("") です。

  • または -

input に日付と時刻の有効な文字列形式が含まれていません。

  • または -

format が空の文字列です。

または

input の時間の部分と AM/PM 指定子が一致していません。

次の例では、 DateTimeOffset.ParseExact(String, String, IFormatProvider) 標準書式指定子とカスタム書式指定子と不変カルチャを含むメソッドを使用して、複数の日付と時刻の文字列を解析します。

string dateString, format;
DateTimeOffset result;
CultureInfo provider = CultureInfo.InvariantCulture;

// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

// Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
dateString = "6/15/2008";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

// Parse date and time with offset without offset//s minutes.
// Should throw a FormatException because "zzz" specifier requires leading
// zero in hours.
dateString = "Sun 15 Jun 2008 8:30 AM -06";
try
{
   result = DateTimeOffset.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
}
// The example displays the following output:
//    06/15/2008 converts to 6/15/2008 12:00:00 AM -07:00.
//    6/15/2008 is not in the correct format.
//    Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00.
//    Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
let provider = CultureInfo.InvariantCulture

// Parse date-only value with invariant culture.
let dateString = "06/15/2008"
let format = "d"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// Parse date-only value without leading zero in month using "d" format.
// Should throw a FormatException because standard short date pattern of
// invariant culture requires two-digit month.
let dateString = "6/15/2008"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// Parse date and time with custom specifier.
let dateString = "Sun 15 Jun 2008 8:30 AM -06:00"
let format = "ddd dd MMM yyyy h:mm tt zzz"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// Parse date and time with offset without offset//s minutes.
// Should throw a FormatException because "zzz" specifier requires leading
// zero in hours.
let dateString = "Sun 15 Jun 2008 8:30 AM -06"
try
    let result = DateTimeOffset.ParseExact(dateString, format, provider)
    printfn $"{dateString} converts to {result}."
with :? FormatException ->
    printfn $"{dateString} is not in the correct format."

// The example displays the following output:
//    06/15/2008 converts to 6/15/2008 12:00:00 AM -07:00.
//    6/15/2008 is not in the correct format.
//    Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00.
//    Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
Dim dateString, format As String  
Dim result As DateTimeOffset
Dim provider As CultureInfo = CultureInfo.InvariantCulture

' Parse date-only value with invariant culture.
dateString = "06/15/2008"
format = "d"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 

' Parse date-only value without leading zero in month using "d" format.
' Should throw a FormatException because standard short date pattern of 
' invariant culture requires two-digit month.
dateString = "6/15/2008"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 

' Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00"
format = "ddd dd MMM yyyy h:mm tt zzz"        
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 

' Parse date and time with offset without offset's minutes.
' Should throw a FormatException because "zzz" specifier requires leading  
' zero in hours.
dateString = "Sun 15 Jun 2008 8:30 AM -06"
Try
   result = DateTimeOffset.ParseExact(dateString, format, provider)
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString())
Catch e As FormatException
   Console.WriteLine("{0} is not in the correct format.", dateString)
End Try 
' The example displays the following output:
'    06/15/2008 converts to 6/15/2008 12:00:00 AM -07:00.
'    6/15/2008 is not in the correct format.
'    Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 8:30:00 AM -06:00.
'    Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.

次の例では、 ISO 8601 に準拠することが予想される文字列の配列を解析します。 例からの出力が示すように、先頭または末尾のスペースを持つ文字列は、範囲外の日付と時刻の要素を含む文字列と同様に、正常に解析されません。

module parseexact_iso8601

open System

let dateStrings =
    [ "2018-08-18T12:45:16.0000000Z"
      "2018/08/18T12:45:16.0000000Z"
      "2018-18-08T12:45:16.0000000Z"
      " 2018-08-18T12:45:16.0000000Z "
      "2018-08-18T12:45:16.0000000+02:00"
      "2018-08-18T12:45:16.0000000-07:00" ]

for dateString in dateStrings do
    try
        let date =
            DateTimeOffset.ParseExact(dateString, "O", null)

        printfn $"""{dateString, -35} --> {date.ToString "yyyy-MM-dd HH:mm:ss.FF zzz"}"""
    with :? FormatException -> printfn $"FormatException: Unable to convert '{dateString}'"


// The example displays the following output:
//      2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//      FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//      FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//      FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//      2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//      2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
using System;

public class Example2
{
   public static void Main()
   {
      string[] dateStrings = { "2018-08-18T12:45:16.0000000Z",
                               "2018/08/18T12:45:16.0000000Z",
                               "2018-18-08T12:45:16.0000000Z",
                               " 2018-08-18T12:45:16.0000000Z ",
                               "2018-08-18T12:45:16.0000000+02:00",
                               "2018-08-18T12:45:16.0000000-07:00" }; 
      
      foreach (var dateString in dateStrings)
      {
         try {
            var date = DateTimeOffset.ParseExact(dateString, "O", null);
            Console.WriteLine($"{dateString,-35} --> {date:yyyy-MM-dd HH:mm:ss.FF zzz}");
         }
         catch (FormatException)
         {
            Console.WriteLine($"FormatException: Unable to convert '{dateString}'");
         }   
      } 
   }
}
// The example displays the following output:
//      2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
//      FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
//      FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
//      FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
//      2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
//      2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00
Public Module Example
   Public Sub Main()
      Dim dateStrings() As String = { "2018-08-18T12:45:16.0000000Z",
                                      "2018/08/18T12:45:16.0000000Z",
                                      "2018-18-08T12:45:16.0000000Z",
                                      " 2018-08-18T12:45:16.0000000Z ",
                                      "2018-08-18T12:45:16.0000000+02:00",
                                      "2018-08-18T12:45:16.0000000-07:00" } 
      
      For Each dateStr In dateStrings
         Try 
            Dim dat = DateTimeOffset.ParseExact(dateStr, "O", Nothing)
            Console.WriteLine($"{dateStr,-35} --> {dat:yyyy-MM-dd HH:mm:ss.FF zzz}")
         Catch  e As FormatException
            Console.WriteLine($"FormatException: Unable to convert '{dateStr}'")
         End Try   
      Next 
   End Sub
End Module
' The example displays the following output:
'      2018-08-18T12:45:16.0000000Z        --> 2018-08-18 12:45:16 +00:00
'      FormatException: Unable to convert '2018/08/18T12:45:16.0000000Z'
'      FormatException: Unable to convert '2018-18-08T12:45:16.0000000Z'
'      FormatException: Unable to convert ' 2018-08-18T12:45:16.0000000Z '
'      2018-08-18T12:45:16.0000000+02:00   --> 2018-08-18 12:45:16 +02:00
'      2018-08-18T12:45:16.0000000-07:00   --> 2018-08-18 12:45:16 -07:00

注釈

このメソッドは ParseExact(String, String, IFormatProvider) 、日付の文字列表現を解析します。この形式は、パラメーターで定義された format 形式である必要があります。 また、日付と時刻の<Date>文字列形式の 、<Time>および要素が指定されたformat順序で表示される必要<Offset>があります。 文字列がこのformatパラメーターとinput一致しない場合、メソッドFormatExceptionは . これに対し、このメソッドは DateTimeOffset.Parse(String, IFormatProvider) 、書式プロバイダー DateTimeFormatInfo のオブジェクトによって認識されるいずれかの形式で日付の文字列表現を解析します。 Parseまた、日付と<Offset>時刻の<Date>文字列表現の 、<Time>および要素を任意の順序で表示することもできます。

formatパラメーターは、1 つの標準書式指定子またはパラメーターの必要な形式を定義する 1 つ以上のinputカスタム書式指定子を含む文字列です。 有効な書式指定コードの詳細については、「 標準の日付と時刻の書式指定文字列」およびカスタム日時書式指定文字列」を参照してください。 オフセットがz存在する必要があることを示す 、zzまたはzzzカスタム書式指定子が含まれている場合formatは、そのオフセットにinput負符号または正符号を含める必要があります。 符号が見つからない場合、メソッド FormatExceptionは .

日付を含むinput必要があるが、時刻を含まない必要がある場合format、結果のDateTimeOffsetオブジェクトには午前 0 時 (0:00:00) の時刻が割り当てられます。 日付ではなく時刻を含むinput必要がある場合format、結果DateTimeOffsetのオブジェクトにはローカル システムの現在の日付が割り当てられます。 オフセットを含むinput必要がない場合formatは、結果DateTimeOffsetのオブジェクトにローカル システムのタイム ゾーン オフセットが割り当てられます。

使用される特定の日付と時刻のinputシンボルと文字列は、標準書式指定子文字列である場合formatinput正確な形式と同様に、パラメーターによってformatProvider定義されます。 パラメーターには formatProvider 、次のいずれかを指定できます。

  • CultureInfo解釈されるカルチャinputを表すオブジェクト。 そのDateTimeFormatプロパティによって返されるオブジェクトはDateTimeFormatInfo、シンボルと書式設定をinput定義します。

  • DateTimeFormatInfo日付と時刻のデータの形式を定義するオブジェクト。

ある場合 formatprovidernull、現在の CultureInfo カルチャに対応するオブジェクトが使用されます。

注意 (呼び出し元)

.NET Framework 4 では、ParseExact解析する文字列に時間コンポーネントと、一致しない AM/PM 指定子が含まれている場合、メソッドは a FormatException をスローします。 .NET Framework 3.5 以前のバージョンでは、AM/PM 指定子は無視されます。

こちらもご覧ください

適用対象

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

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、日付と時刻を表す文字範囲を等価の DateTimeOffset に変換します。 日付と時刻を表すための書式は、指定した書式と完全に一致する必要があります。

public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member ParseExact : ReadOnlySpan<char> * ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As ReadOnlySpan(Of Char), format As ReadOnlySpan(Of Char), formatProvider As IFormatProvider, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTimeOffset

パラメーター

input
ReadOnlySpan<Char>

日付と時刻を表す文字範囲です。

format
ReadOnlySpan<Char>

input の有効な書式を定義する書式指定子を含む文字範囲です。

formatProvider
IFormatProvider

input に関するカルチャ固有の書式情報を提供するオブジェクト。

styles
DateTimeStyles

input で使用可能な書式を示す、列挙値のビットごとの組み合わせ。

戻り値

DateTimeOffset

formatformatProvider、および styles の各パラメーターで指定された書式に従って表記された、input パラメーターに含まれる日時と等価のオブジェクト。

例外

オフセットが -14 時間より小さいか、14 時間を超えています。 または、パラメーターに styles サポートされていない値が含まれています。 または、パラメーターには styles 、一緒に DateTimeStyles 使用できない値が含まれています。

input は空の文字範囲です。 または、input に日付と時刻の有効な文字列形式が含まれていません。 または、format は空の文字範囲です。 または、時間コンポーネントと AM/PM 指定子が input 一致しません。

注釈

このメソッドは、日付を表す文字スパンを解析します。これは、パラメーターで定義された format 形式である必要があります。 また、日付と時刻の<Date>文字列表現の 、<Time>および要素が指定されたformat順序で表示される必要<Offset>があります。 パターンとformat一致しない場合input、メソッドFormatExceptionは . これに対し、このメソッドは DateTimeOffset.Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) 、書式プロバイダー DateTimeFormatInfo のオブジェクトによって認識されるいずれかの形式で日付の文字列表現を解析します。 Parseまた、日付と<Offset>時刻の<Date>文字列表現の 、<Time>および要素を任意の順序で表示することもできます。

formatパラメーターは、1 文字の標準書式指定子またはパラメーターの必要な形式を定義する 1 つ以上のinputカスタム書式指定子を含む文字スパンです。 有効な書式指定コードの詳細については、「 標準の日付と時刻の書式指定文字列」およびカスタム日時書式指定文字列」を参照してください。 オフセットがz存在する必要があることを示す 、zzまたはzzzカスタム書式指定子が含まれている場合formatは、そのオフセットにinput負符号または正符号を含める必要があります。 符号が見つからない場合、メソッド FormatExceptionは .

日付を含むinput必要があるが、時刻を含まない必要がある場合format、結果のDateTimeOffsetオブジェクトには午前 0 時 (0:00:00) の時刻が割り当てられます。 日付ではなく時刻を含むinput必要がある場合format、結果DateTimeOffsetのオブジェクトにはローカル システムの現在の日付が割り当てられます。 オフセットを含むinput必要がない場合formatは、結果DateTimeOffsetのオブジェクトにローカル システムのタイム ゾーン オフセットが割り当てられます。

使用される特定の日付と時刻のinputシンボルと文字列は、標準書式指定子である場合formatinput正確な形式と同様に、パラメーターによってformatProvider定義されます。 パラメーターには formatProvider 、次のいずれかを指定できます。

  • CultureInfo解釈されるカルチャinputを表すオブジェクト。 そのDateTimeFormatプロパティによって返されるオブジェクトはDateTimeFormatInfo、シンボルと書式設定をinput定義します。

  • DateTimeFormatInfo日付と時刻のデータの形式を定義するオブジェクト。

ある場合 formatprovidernull、現在の CultureInfo カルチャに対応するオブジェクトが使用されます。

適用対象

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

指定した書式、カルチャ固有の書式情報、およびスタイルを使用して、日付と時刻の文字列表現を含む文字範囲を等価の DateTimeOffset に変換します。 日付と時刻を表すための書式は、指定した書式のいずれかと完全に一致する必要があります。

public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTimeOffset ParseExact (ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member ParseExact : ReadOnlySpan<char> * string[] * IFormatProvider * System.Globalization.DateTimeStyles -> DateTimeOffset
Public Shared Function ParseExact (input As ReadOnlySpan(Of Char), formats As String(), formatProvider As IFormatProvider, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTimeOffset

パラメーター

input
ReadOnlySpan<Char>

変換する日付と時刻を含む文字範囲。

formats
String[]

input の有効な書式を定義する書式指定子の配列。

formatProvider
IFormatProvider

input に関するカルチャ固有の書式情報を提供するオブジェクト。

styles
DateTimeStyles

input で使用可能な書式を示す、列挙値のビットごとの組み合わせ。

戻り値

DateTimeOffset

formatsformatProvider、および styles の各パラメーターで指定された書式に従って表記された、input パラメーターに含まれる日時と等価のオブジェクト。

例外

オフセットが -14 時間より小さいか、14 時間を超えています。 または、サポートされていない値が styles に含まれています。 または、パラメーターには styles 、一緒に DateTimeStyles 使用できない値が含まれています。

input は空の文字範囲です。 または、input に日付と時刻の有効な文字列形式が含まれていません。 または、有効な書式指定子を含む要素 formats がありません。 または、時間コンポーネントと AM/PM 指定子が input 一致しません。

注釈

このメソッドは、パラメーターに割り当てられたパターンのいずれかに一致する日付を表す文字スパンを formats 解析します。 これらのパターンのいずれかがパラメーターによって定義されたstylesバリエーションと一致しない場合input、メソッドFormatExceptionは . 複数の書式設定パターンと比較すると input 、このオーバーロードはメソッドと同じように DateTimeOffset.ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles) 動作します。

formatsこのパラメーターは、1 つの標準書式指定子またはパラメーターの可能なパターンを定義する 1 つ以上のカスタム書式指定子を要素にinput含む文字列配列です。 メソッドを呼び出すときは、 input これらのパターンのいずれかに一致する必要があります。 有効な書式指定コードの詳細については、「 標準の日付と時刻の書式指定文字列」およびカスタム日時書式指定文字列」を参照してください。 一致した要素にformatsオフセットが存在inputする必要があることを示す 、zzまたはzzzカスタム書式指定子が含まれているz場合、そのオフセットには負符号または正符号を含める必要があります。 符号が見つからない場合、メソッド FormatExceptionは .

重要

このオーバーロードのパラメーターを formats 使用して複数の形式を指定すると、多くのユーザーが日付と時刻を入力するときのフラストレーションを軽減できます。 特に、複数の入力パターンを定義する機能を使用すると、アプリケーションは、月、日、時間、分、秒の先頭のゼロを含めたり欠けたりできる日付と時刻の表現を処理できます。

一致した要素に formats 日付が含まれている必要 input があるが、時刻が含まれていない場合、結果の DateTimeOffset オブジェクトには午前 0 時 (0:00:00) の時刻が割り当てられます。 一致した要素に formats 日付ではなく時刻を含む必要がある input 場合、結果の DateTimeOffset オブジェクトにはローカル システムの現在の日付が割り当てられます。 一致した要素に formats オフセットを含む input 必要がない場合、結果の DateTimeOffset オブジェクトのオフセットはパラメーターの styles 値によって異なります。 含まれているAssumeLocal場合styles、ローカル タイム ゾーンのオフセットがオブジェクトにDateTimeOffset割り当てられます。 含まれているAssumeUniversal場合styles、協定世界時 (UTC) オフセット (+00:00) がオブジェクトにDateTimeOffset割り当てられます。 どちらの値も指定しないと、ローカル タイム ゾーンのオフセットが使用されます。

使用される特定の日付と時刻の input シンボルと文字列は、パラメーターによって formatProvider 定義されます。 一致する要素formatsが標準書式指定子文字列のinput場合、正確な書式についても同様です。 パラメーターには formatProvider 、次のいずれかを指定できます。

ある場合 formatprovidernull、現在の CultureInfo カルチャに対応するオブジェクトが使用されます。

このパラメーターは styles 、入力文字列で空白を許可するかどうかを定義し、明示的なオフセット コンポーネントのない文字列を解析する方法を示し、解析操作の一部として UTC 変換をサポートします。 列挙体のすべてのメンバーは、次を DateTimeStyles 除いて NoCurrentDateDefaultサポートされています。 次の表に、サポートされている各メンバーの効果を示します。

DateTimeStyles のメンバー 動作
AdjustToUniversal input解析し、必要に応じて UTC に変換します。 これは、文字列を解析してから、返されたDateTimeOffsetオブジェクトのメソッドをDateTimeOffset.ToUniversalTime呼び出すことと同じです。
AssumeLocal 一致した要素に formats オフセット値を含む input 必要がない場合、返される DateTimeOffset オブジェクトにはローカル タイム ゾーンのオフセットが指定されます。 これが既定値です。
AssumeUniversal 一致した要素に formats オフセット値を含む input 必要がない場合、返される DateTimeOffset オブジェクトには UTC オフセット (+00:00) が与えられます。
AllowInnerWhite で指定formatされていない内側の空白を含めることができますinput。 日付と時刻のコンポーネントの間と個々のコンポーネント (オフセットを除く) 内に余分な空白が表示される可能性があり、文字列の解析時には無視されます。
AllowLeadingWhite で指定されていない先頭のスペースをformats含めることができますinput。 文字列を解析する場合、これらは無視されます。
AllowTrailingWhite で指定されていない末尾のスペースをformats含めることができますinput。 文字列を解析する場合、これらは無視されます。
AllowWhiteSpaces で指定されていない先頭、末尾、および内側のスペースをformats含めることができますinput。 文字列の解析時に、一致する要素 formats で指定されていない余分な空白文字はすべて無視されます。
None で追加の空白が許可されていないことを input示します。 空白は、一致する要素の特定の formats 要素で指定されたとおりに表示する必要があります。 これは既定の動作です。
RoundtripKind 構造体にプロパティが DateTimeOffset 含まれていないため、 Kind 効果はありません。

適用対象