I have following C# method:
DateTime ConvertStringToDate(string dateInString)
{
try {
//string SSD = dateInString;
//DateTime date = Convert.ToDateTime(SSD);
//string strDate = String.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", date);
//return Convert.ToDateTime(strDate);
return DateTime.ParseExact(dateInString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
catch (Exception) { }
return DateTime.Today;
}
}
The code in comment is another way I tried before.
I am in India and developing an ASP.NET WebForms application for my client in US. On one of its forms my client will enter the date in TextBox
like 6/20/2018 which is MM/dd/yyyy format.
But, in both the ways I am getting this error:
System.FormatException: 'String was not recognized as a valid DateTime.'
return DateTime.ParseExact(dateInString, "M/d/yyyy", CultureInfo.InvariantCulture);
The difference between my answer and Fabulous' one is that I also shortened dd
to d
so if your user writes 6/6/2018
it will work too