Search code examples
c#sqldatetimedatagridviewdatetimepicker

String '12/20/2022 12:00:00 AM' was not recognized as a valid DateTime


Code & error

DateTime dt = DateTime.ParseExact(dgvSP.CurrentRow.Cells[5].Value.ToString(), "dd-MM-YYYY", CultureInfo.InvariantCulture);
dtpQLSPnsx.Value = dt;

Why my datetimepicker value is '12/20/2022 12:00:00 AM' but it show on datagridview only 12/20/2022

I am trying to convert datetimepicker value form '12/20/2022 12:00:00 AM' to '12/20/2022' and I also try to change format but still didnt work


Solution

  • your date is not in the correct format when you are passing it to the DateTime.ParseExact method. There is no month with a value of 20. so your date is 20 Dec.

    var cdate = "12/20/2022 12:00:00 AM";
    var dt = DateTime.ParseExact(cdate, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
    var date = dt.ToString("MM/dd/yyyy");