String was not recognized as a valid DateTime “ format dd/MM/yyyy”

String was not recognized as a valid DateTime “ format dd/MM/yyyy”

Asked on December 20, 2018 in C#.
Add Comment


  • 4 Answer(s)

    Try this code DateTime.ParseExact.

    this.Text="22/11/2009";
    DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
    
    Answered on December 20, 2018.
    Add Comment

    try with MM/dd/yyyy hh:mm:ss tt instead of dd/MM/yyyy

    if you use DateTime.ParseExact The format of the string representation must match a specified format exactly or an exception is thrown.

    if you need only the date

    DateTime pDate = DateTime.ParseExact("05/28/2013 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
    var dateOnly= pDate.ToString("dd/MM/yyyy");

    As per your comment, database contain data with Type ‘Date’, So you can read it directly as DateTime. You can convert to string by calling ToString with the expected Format.

    Answered on January 15, 2019.
    Add Comment
    use this
    DateTime startDate; it is output date
    string[] formats = {
    “d.MM.yyyy”,
    “dd.MM.yyyy”,
    “dd.M.yyyy”,
    “d.M.yyyy”,
    “d/MM/yyyy”,
    “dd/MM/yyyy”,
    “dd/M/yyyy”,
    “d/M/yyyy”
    }; // these you can change as per your current date
    If DateTime.TryParseExact(“your date”, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, startDate) Then
    {
    //out date is start date,
    }
    Answered on January 15, 2019.
    Add Comment
    string dateString = @"20/05/2012";
    //The following code throws
    //FormatException: String was not recognized as a valid DateTime
    DateTime date = Convert.ToDateTime(dateString);
    Answered on January 28, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.