EF Core 6 & C# : converting from string to datetime not working

220 Views Asked by At

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)

1

There are 1 best solutions below

13
Yong Shun On

Use DateTime.TryParseExact method when you have a specific date string format to convert into DateTime.

While the method returns a boolean value indicates the date string can be converted into DateTime. To get the DateTime value, you need to get it from the out parameter.

Also, you will get the compilation error from string as it is a type (reserved keyword). You should either rename or use the @ prefix.

var @string = "12/28/2023";

bool isDate = DateTime.TryParseExact(@string, 
    "MM/dd/yyyy", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None, 
    out DateTime dtmDate);