1

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.

4 Answers 4

7

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)
Sign up to request clarification or add additional context in comments.

2 Comments

its throwing a error like this String was not recognized as a valid DateTime.
It's likely that you have to specify the appropriate date format. I'll update my answer.
3

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)

Comments

0

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.

2 Comments

its throwing a error like this String was not recognized as a valid DateTime.
My Date Format is dd/mm/yyyy like 29/11/2011 Indian Date Format
0

Use overloaded version of the function:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.