27

I am developing asp.net site using vb framework 3.5.

Im having difficulties converting string data into Date I tried using cdate function,

I have a variable sdate which is a string variable and date is stored in it which comes from textbox as dd/mm/yyyy now i want to convert this string into a Date variable as i need to perform the operations as Add a day or Subtract a day.

Please guide me how to go about this. i get the error on 3rd line as,String was not recognized as a valid DateTime. I have tried to do as follows but the error comes

Dim sdate As String 
Dim expenddt As Date
expenddt = Date.Parse(edate)
expenddt = expenddt.AddDays(-1)

But i get the error as

Conversion from String to type Date is not valid.

How can I get a Date from the string?

jww
  • 83,594
  • 69
  • 338
  • 732
Ishan
  • 3,818
  • 28
  • 78
  • 149

5 Answers5

55

You should have to use Date.ParseExact or Date.TryParseExact with correct format string.

 Dim edate = "10/12/2009"
 Dim expenddt As Date = Date.ParseExact(edate, "dd/MM/yyyy", 
            System.Globalization.DateTimeFormatInfo.InvariantInfo)

OR

 Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
 Dim expenddt As Date = Date.ParseExact(edate, format,  
     System.Globalization.DateTimeFormatInfo.InvariantInfo, 
     Globalization.DateTimeStyles.None)

OR

Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
Dim expenddt As Date
Date.TryParseExact(edate, format, 
    System.Globalization.DateTimeFormatInfo.InvariantInfo, 
    Globalization.DateTimeStyles.None, expenddt)
kv-prajapati
  • 90,019
  • 18
  • 141
  • 178
6

Nobody mentioned this, but in some cases the other method fails to recognize the datetime...

You can try this instead, which will convert the specified string representation of a date and time to an equivalent date and time value

string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
MessageBox.Show(oDate.Day + " " + oDate.Month + "  " + oDate.Year );
Inc33
  • 1,278
  • 1
  • 15
  • 22
5

Try to see if the following code helps you:

Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)
Fabien
  • 4,207
  • 1
  • 15
  • 33
Doug Null
  • 7,131
  • 14
  • 55
  • 116
2

Try to use DateTime.ParseExact method, in which you can specify both of datetime mask and original parsed string. You can read about it here: MSDN: DateTime.ParseExact

Dmitry Bastron
  • 654
  • 3
  • 10
  • 1
    This is surely VB6 question as I can see OP's code `expenddt = CDate(edate)` – Rahul Dec 26 '11 at 10:04
  • 2
    @Rahul: Using the Visual-Basic Type Conversion Function does not mean that he uses VB6: http://msdn.microsoft.com/en-us/library/s2dy91zy%28v=VS.100%29.aspx – Tim Schmelter Dec 26 '11 at 13:21
2

Try converting date like this:

    Dim expenddt as Date = Date.ParseExact(edate, "dd/mm/yyyy", 
System.Globalization.DateTimeFormatInfo.InvariantInfo);

Hope this helps.

AlphaMale
  • 23,514
  • 4
  • 57
  • 77