locked
System.FormatException: 'String was not recognized as a valid DateTime.' RRS feed

  • Question

  • User-1355965324 posted

    I am trying to convert the string variable into datetime 

    string clockingTime = attlog.AttendanceDate + " " + attlog.Hrs + ":" + attlog.Mins + ":00";
    DateTime clockDate = DateTime.ParseExact(attlog.AttendanceDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) But the error is coming is as given below

    System.FormatException: 'String was not recognized as a valid DateTime.' The value  10/07/2019 7:10:00 is stored in the variable clockingTime . Please help me to convert it into datetime

    Regards

    Pol

    Monday, July 8, 2019 3:51 PM

All replies

  • User475983607 posted

    Clearly the string value in clockingTime ( 10/07/2019 7:10:00) does not match the date format in ParseExact; yyyy-MM-dd HH:mm:ss.  the two strings mush have matching formats.  Fix one.

    Monday, July 8, 2019 5:35 PM
  • User711641945 posted

    Hi  polachan,

    Your parameters of the string type do not match the format.There is a working demo like below:

    public DateTime Parsetime()
    
            {
                AttLog attlog = new AttLog() { AttendanceDate="2019/07/09",Hrs="15",Mins="14"}; 
                string clockingTime = attlog.AttendanceDate + " " + attlog.Hrs + ":" + attlog.Mins + ":00";
                DateTime clockDate = DateTime.ParseExact(clockingTime, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
                return clockDate;
            }
    

    You could refer to: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.8

    Best Regards,

    Rena

    Tuesday, July 9, 2019 7:00 AM