Kishore Kumar
Kishore Kumar

Reputation: 12874

Converting Date From TextBox To Date In ASP.Net

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.

Upvotes: 1

Views: 21126

Answers (4)

Dario Solera
Dario Solera

Reputation: 5804

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)

Upvotes: 7

Jay
Jay

Reputation: 6017

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)

Upvotes: 3

veljkoz
veljkoz

Reputation: 8514

Use overloaded version of the function:

 DateTime value = DateTime.Parse(txtFrom.Text,  new CultureInfo("gu-IN", false));

where "gu-IN" is for Gujarati (India)

Upvotes: 0

Wouter de Kort
Wouter de Kort

Reputation: 39898

You can directly cast a string to DateTime. You need to use the DateTime.Parse function to parse a string to a DateTime.

The syntax can be found here.

Upvotes: 0

Related Questions