Converting Date From TextBox To Date In ASP.Net
20,087
Solution 1
In general, try to avoid using old VB functions like CDate
. In this case, you should use the Parse
method:
Dim ts As TimeSpan
ts = DateTime.Parse(txtTo.Text) - DateTime.Parse(txtFrom.Text)
Or, if you know the date format in advance:
Dim fmt As String = "dd/MM/yyyy"
Dim ts As TimeSpan
ts = DateTime.ParseExact(txtTo.Text, fmt, Nothing) - DateTime.ParseExact(txtFrom.Text, fmt, Nothing)
Solution 2
Try using ParseExact like:
Dim s As String = txtFrom.Text.trim
Dim pattern As String = "dd/MM/yyyy"
Dim parsedDate As Date = Date.ParseExact(s, pattern, Nothing)
As that way you can specify the format of the string that is used.
More direct to your example:
Dim pattern As String = "dd/MM/yyyy"
ts = Date.ParseExact(txtTo.Text, pattern, Nothing) - Date.ParseExact(txtFrom.Text, pattern, Nothing)
Author by
Kishore Kumar
OpenText Content Server Developer, Windows Developer, Web Designer & Developer. Interested in VB.Net,C#,WPF,ASP.Net,ASP.Net MVC,XAML,WCF,OScript, BackboneJS, Marionette http://www.dignaj.com/kishore/
Updated on July 06, 2022Comments
-
Kishore Kumar almost 2 years
I want to get the difference of date from Two TextBox say to and from dates..
My Code is here
Dim ts As TimeSpan ts = CDate(txtTo.Text) - CDate(txtFrom.Text) txtDays.Text = ts.Days() + 1
but this code is throwing an error like this
Conversion from string "16/11/2011" to type 'Date' is not valid.
-
Kishore Kumar over 12 yearsits throwing a error like this
String was not recognized as a valid DateTime.
-
Kishore Kumar over 12 yearsMy Date Format is dd/mm/yyyy like 29/11/2011 Indian Date Format
-
Kishore Kumar over 12 yearsits throwing a error like this
String was not recognized as a valid DateTime.
-
Dario Solera over 12 yearsIt's likely that you have to specify the appropriate date format. I'll update my answer.