[VB.NET] 日付文字列を日付型に変換する方法

VB.NETで日付文字列を日付型に変換する方法

DateTime.Parseメソッドを使用する


StringからDateTimeへの変換


<VB.NET>
'DateTime.Parse : 現在のカルチャを使用して変換する
Dim d As String
Dim dt As DateTime

d = "2014/12/24 15:32:12"
dt = DateTime.Parse(d)
Console.WriteLine(dt)
'出力 : 2014/12/24 15:32:12

d = "2014/12/24"
dt = DateTime.Parse(d)
Console.WriteLine(dt)
'出力 : 2014/12/24 0:00:00


<VB.NET>
'DateTime.ParseExact : カルチャを指定して変換する
Dim d, c As String
Dim dt As DateTime

d = "2014/12/24 15:32:12"
c = "yyyy/MM/dd HH:mm:ss"
dt = DateTime.ParseExact(d, c, Nothing)
Console.WriteLine(dt)
'出力 : 2014/12/24 15:32:12

d = "20141224153212"
c = "yyyyMMddHHmmss"
dt = DateTime.ParseExact(d, c, Nothing)
Console.WriteLine(dt)
'出力 : 2014/12/24 15:32:12

d = "2014年12月24日15時32分12秒"
c = "yyyy年MM月dd日HH時mm分ss秒"
dt = DateTime.ParseExact(d, c, Nothing)
Console.WriteLine(dt)
'出力 : 2014/12/24 15:32:12


<VB.NET>
'文字列操作との組み合わせ
Dim d, c As String
Dim dt As DateTime

d = "201412241532"
c = "yyyyMMddHHmmss"
dt = DateTime.ParseExact(d.PadRight(14, "0"), c, Nothing)
Console.WriteLine(dt)
'出力 : 2014/12/24 15:32:00

d = "201412241532 2"
c = "yyyyMMddHHmmss"
dt = DateTime.ParseExact(d.Replace(" ", "0"), c, Nothing)
Console.WriteLine(dt)
'出力 : 2014/12/24 15:32:02

d = "20141224153 1"
c = "yyyyMMddHHmmss"
dt = DateTime.ParseExact(d.Replace(" ", "0").PadRight(14, "0"), c, Nothing)
Console.WriteLine(dt)
'出力 : 2014/12/24 15:30:10


○関連サイト
日時を表す文字列をDateTimeオブジェクトに変換する
日付や時刻の文字列をDateTimeオブジェクトに変換するには?
VB.NET DateからStringへ変換、StringからDateへ変換 について

このブログの人気の投稿

[Access VBA] SQLServerのテーブルをODBC接続でAccessにインポートする方法

[Access SQL] Access SQLで切り捨てを行う方法

[SQL] COUNTするときに条件指定する方法