Convert.Todatetime and datetime.Parse

Momo

Member
Joined
May 30, 2006
Messages
21
Programming Experience
Beginner
Helo all, I'm confused with this two function. As I googled from most fourms, what i get is:

DateTime.Parse (or CDate) is useful to convert a string to a DateTime based
on the current regional settings in Control Panel.

DateTime.ParseExact is useful to convert a string to a DateTime based on a
specific format or a specific region/culture.

But, how it's functionality work different? What I means is as I will get "string cant convert to datetime" error but for datetime. But, sometimes it work fine.

As in my case I use datetimepicker to exact the date, likes say :
Dim strStartDate as string = Me.dtp1.Text & " " & "Me.ComboHours.SelectedItems & " : " & Me.ComboMin.SelectedItems & " : " & " 00 "
Dim dtStartDate as datetime = CDate(strStartDate)

Can anybody point this out? Thanks in advance.
 
You should ONLY use CDate to cast an Object reference to Date. You should not use CDate to convert anything. Here's an example of where CDate would be appropriate:
VB.NET:
Dim myArrayList As New ArrayList

myArrayList.Add(#1/01/200#)

Dim myDate As Date = CDate(myArrayList(0))
The ArrayList returns an Object reference, but we know that the object it refers to is type Date, so it is appropriate to use CDate to cast the Object reference as type Date.

You would generally use Date.Parse if you have a string that represents a date and/or time in a format that is standard for the current system. Convert.ToDateTime is basically the same.

You would generally use Date.ParseExact if you have a string that represents a date and/or time in a known format that is not standard, for instance "yyyyMMdd".

You would generally use Date.TryParse if you have a string that you believe represents a date and/or time but you are not positive.

You should almost never use the Text property of a DateTimePicker. The DTP control has a Value property that IS a Date object. If you want to get a date and time then you should set the Format to Custom and the CustomFormat to something like "d/MM/yyyy HH:mm".
 
Back
Top