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

前端 未结 13 1130
一整个雨季
一整个雨季 2020-11-22 05:30

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.

this.Text=\"22/11/2009\";

DateTime date = DateTime.Parse(         


        
相关标签:
13条回答
  • 2020-11-22 06:02
    private DateTime ConvertToDateTime(string strDateTime)
    {
    DateTime dtFinaldate; string sDateTime;
    try { dtFinaldate = Convert.ToDateTime(strDateTime); }
    catch (Exception e)
    {
    string[] sDate = strDateTime.Split('/');
    sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
    dtFinaldate = Convert.ToDateTime(sDateTime);
    }
    return dtFinaldate;
    }
    
    0 讨论(0)
  • 2020-11-22 06:06

    After spending lot of time I have solved the problem

     string strDate = PreocessDate(data);
     string[] dateString = strDate.Split('/');
     DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
    
    0 讨论(0)
  • 2020-11-22 06:06

    You can use also

    this.Text = "22112009";
    DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
                                        Convert.ToInt32(this.Text.Substring(2,2)), // Month
                                        Convert.ToInt32(this.Text.Substring(0,2)));// Day
    
    0 讨论(0)
  • 2020-11-22 06:07

    use this to convert string to datetime:

    Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
    
    0 讨论(0)
  • 2020-11-22 06:11

    You need to call ParseExact, which parses a date that exactly matches a format that you supply.

    For example:

    DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
    

    The IFormatProvider parameter specifies the culture to use to parse the date.
    Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
    If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.

    0 讨论(0)
  • 2020-11-22 06:11

    Based on this reference, the next approach worked for me:

    // e.g. format = "dd/MM/yyyy", dateString = "10/07/2017" 
    var formatInfo = new DateTimeFormatInfo()
    {
         ShortDatePattern = format
    };
    date = Convert.ToDateTime(dateString, formatInfo);
    
    0 讨论(0)
提交回复
热议问题