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
}
OR
Simply
string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null);
Also read:
You can pass your date in the code below
string formattedDate = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
If you have datetime string and want to convert it into Datetime
DateTime myDate = DateTime.ParseExact("2022-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
You can provide format with DateTime.ParseExact()
OR
DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
// handle parse failure
}
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly