Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to a datetime

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?

like image 209
Ishan Avatar asked Dec 26 '11 09:12

Ishan


People also ask

How do I change the format of a time in Python?

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.

How do I convert a string to a date in TypeScript?

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.


2 Answers

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) 
like image 95
KV Prajapati Avatar answered Oct 08 '22 09:10

KV Prajapati


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 ); 
like image 24
Inc33 Avatar answered Oct 08 '22 10:10

Inc33