I am using the code below to convert my string which is in the format "dd/MM/yyyy" into datetime
//DateStr = 19/02/2017 for example Datetime date = Convert.ToDatetime(Datestr);
but it is throwing a runtime error of Invalid type, so how should I convert it into valid Datetime value without getting any error?
You should use DateTime.ParseExact
, to get the correct results
DateTime dt=DateTime.ParseExact("19/02/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Read more about Datetime.ParseExact
Or You can use DateTime.TryParseExact , it is also same, code will be like this
DateTime dt;
if (DateTime.TryParseExact("19/02/2017", "dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//date is valid, do something here
}
You can pass your date in the code below
string formattedDate = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly