日時には様々な表記が存在するため、文字列からDateTime・DateTimeOffsetへの変換はその逆よりも考慮すべき事柄が多く、すべての表記に対応しようとすると複雑になります。 まずはシンプルな例として、Parseメソッドを使った例を見ていきます。
DateTime.ParseおよびDateTimeOffset.Parseメソッドは、引数で与えられた文字列を解析し、DateTime・DateTimeOffsetに変換た結果を返します。 Parseメソッドは、標準の書式としてサポートされている形式での解析を試み、解析できた場合はその結果を返します。
Parseメソッドに指定された文字列が日時として解析できない場合や、日時として不正な形式・値の場合は、例外FormatExceptionがスローされます。
DateTime/DateTimeOffset.Parseメソッドで不正な日時の形式・値の文字列を変換する
Imports System
Class Sample
Shared Sub Main()
Dim inputs() As String = New String() { _
"29 Feb 2012", _
"1/2/3", _
"31 Feb 2013", _
"1 Apr 10000", _
"27:00:00", _
"2013-04-01T15:00:30.1230000+15:00", _
"+09:00", _
"0123456" _
}
' 文字列をDateTimeに変換
For Each input As String In inputs
Try
Console.WriteLine("{0,-35} -> {1}", input, DateTime.Parse(input))
Catch ex As FormatException
' Parseメソッドで変換できない場合は、FormatExceptionがスローされる
Console.WriteLine("{0,-35} -> FormatException", input)
End Try
Next
Console.WriteLine()
' 文字列をDateTimeOffsetに変換
For Each input As String In inputs
Try
Console.WriteLine("{0,-35} -> {1}", input, DateTimeOffset.Parse(input))
Catch ex As FormatException
Console.WriteLine("{0,-35} -> FormatException", input)
End Try
Next
Console.WriteLine()
End Sub
End Class
実行結果
29 Feb 2012 -> 2012/02/29 0:00:00 1/2/3 -> 2001/02/03 0:00:00 31 Feb 2013 -> FormatException 1 Apr 10000 -> FormatException 27:00:00 -> FormatException 2013-04-01T15:00:30.1230000+15:00 -> 2013/04/02 0:00:30 +09:00 -> FormatException 0123456 -> FormatException 29 Feb 2012 -> 2012/02/29 0:00:00 +09:00 1/2/3 -> 2001/02/03 0:00:00 +09:00 31 Feb 2013 -> FormatException 1 Apr 10000 -> FormatException 27:00:00 -> FormatException 2013-04-01T15:00:30.1230000+15:00 -> FormatException +09:00 -> FormatException 0123456 -> FormatException
Parseメソッドで変換できない場合にFormatExceptionがスローされることを望まない場合や、変換できた場合・できなかった場合で処理を分岐させたいような場合は、Parseメソッドの代わりにTryParseメソッドを使うこともできます。