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?
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
Use the Date() constructor to convert a string to a Date object in TypeScript, e.g. const date = new Date('2024-07-21') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.
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)
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With