Help converting a string date to a DateTime

2020-03-26 05:06发布

问题:

I'm using the Ajax control toolkit calendar extender on a textbox with a submit button. Simple.

The debugger shows that the text is properly being transferred to calling method, but this line of conversion code converts textbox text to 1/1/0001 12:00:00 AM. The text box date is this: 4/15/2011

DateTime txtMyDate = Convert.ToDateTime(txtDate.Text);

What am I doing wrong?

回答1:

You should use the DateTime.Parse() method:

DateTime txtMyDate = DateTime.Parse(txtDate.Text);

As mentioned you can also use DateTime.ParseExact() using a similar syntax as shown:

DateTime txtMyDate = DateTime.ParseExact(txtDate.Text, 
                                         [string format], 
                                         [IFormatProvider provider]);

Parse vs ParseExact:

Parse() - assumes the data is valid and does its best to fit it into the type, forcing things that seem vaguely ridiculous when a developer has a chance to invoke common sense.

ParseExact() - only allows the exact format specified and will throw on any variation.

Source on Parse vs ParseExact



回答2:

There are many ways to convert text to a DateTime, try this one:

DateTime txtMyDate = 
  DateTime.ParseExact(txtDate.Text, "M/d/yyyy", CultureInfo.InvariantCulture);

Edit: forgot the culture info argument



回答3:

Use DateTime.ParseExact to extract your date value from a formated date string:

DateTime dateValue = 
   DateTime.ParseExact(stringDateValue, "M/d/yyyy", 
        CultureInfo.InvariantCulture);


回答4:

Try

DateTime instance = DateTime.Parse( txtDate.Text ) ;

which is [somewhat] flexible about what it will accept. Alternatively, DateTime.ParseExact() will give you move control over the conversion.



标签: c# asp.net