Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between CType(str,DateTime) and DateTime.Parse(str)

I want to convert str into DateTime.

For that which option should I used in VB.NET? And Why?

like image 708
Pratik Soni Avatar asked Dec 05 '25 04:12

Pratik Soni


1 Answers

I tend to do it like this:

Dates "disguised" as Object

If I know the object is a datetime I use CType:

Dim table As New DataTable("Table")

table.Columns.Add("DATETIME_COLUMN", GetType(DateTime))
table.Rows.Add(Date.Now)
table.AcceptChanges()

Dim d As DateTime = CType(table.Rows(0).Item("DATETIME_COLUMN"), DateTime)

Strings

When dealing with strings I use DateTime.Parse. Notice that you can pass a cultureinfo.

Dim d As DateTime = DateTime.Parse("10.02.2014", New System.Globalization.CultureInfo("nb-NO"))

Unknown/mixed types

Finally, if I cannot be sure of the datatype, I use Convert.ToDateTime:

Dim d As DateTime = Convert.ToDateTime(obj, New System.Globalization.CultureInfo("nb-NO"))
like image 96
Bjørn-Roger Kringsjå Avatar answered Dec 07 '25 16:12

Bjørn-Roger Kringsjå



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!