I tried to convert an entered string date '12/23/2023' to a datetime, but it's not working.
I tried it using:
Code snippet #1:
DateTime? dtmDate = null;
value = "12/23/2023";
string[] dateString = value.Split('/');
dtmDate = Convert.ToDateTime(dateString[0] + "/" + dateString[1] + "/" + dateString[2]);
// Expected output : string "12/28/2023" to datetime: 12/18/2023
Code snippet #2:
var string = "12/28/2023"
dtmDate = DateTime.TryParseExact(string, "MM/dd/yyyy",CultureInfo.InvariantCulture);
This is also not working.. the format of my SQL is:
2023-12-23 00:00:00.000
Please help me out
I get this error:
System.FormatException: String '12/23/2023' was not recognized as a valid DateTime.
at System.DateTime.Parse(String s)
Use
DateTime.TryParseExactmethod when you have a specific date string format to convert intoDateTime.While the method returns a boolean value indicates the date string can be converted into DateTime. To get the
DateTimevalue, you need to get it from theoutparameter.Also, you will get the compilation error from
stringas it is a type (reserved keyword). You should either rename or use the@prefix.