String was not recognized as a valid DateTime “ fo

2018-12-31 10:01发布

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(this.Text);

What is the problem ? It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?

Edit

What are the differences between Parse and ParseExact?

Edit 2

Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.

Which answer is better considering all aspects like type saftey, performance or something you feel like

14条回答
荒废的爱情
2楼-- · 2018-12-31 10:28
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;
}
查看更多
骚的不知所云
3楼-- · 2018-12-31 10:32

Change Manually :

string s = date.Substring(3, 2) +"/" + date.Substring(0, 2) + "/" + date.Substring(6, 4);

From 11/22/2015 it will be converted in 22/11/2015

查看更多
不再属于我。
4楼-- · 2018-12-31 10:33

Worked for me below code:

DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));

Namespace

using System.Globalization;
查看更多
牵手、夕阳
5楼-- · 2018-12-31 10:33

An easy way without external references:

public string FormatDate(string date, string format)
{
   try {
      return DateTime.Parse(date).ToString(format);
   }
   catch (FormatException) 
   {
      return string.Empty;
   }
}
查看更多
零度萤火
6楼-- · 2018-12-31 10:35

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);
查看更多
一个人的天荒地老
7楼-- · 2018-12-31 10:35

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
查看更多
登录 后发表回答