3

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
  • So, what do you want is a DateTime value that holds a date only ?! Commented May 11, 2011 at 21:19

4 Answers 4

12

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

Sign up to request clarification or add additional context in comments.

4 Comments

Weirdly, MSDN says that Convert.ToDateTime(string) actually calls DateTime.Parse(), so I'm kinda curious as to why calling DateTime.Parse() directly would work if Convert.ToDateTime() didn't.
You are still receiving 1/1/0001 12:00:00 AM as your DateTime? If that is occurring then it is probably an issue with the data not being passed in properly or a value isn't being set.
yes it was my fault. As both this answer and Matt Greer's answer is correct, I am choosing this one as it explains the difference between Parse and ParseExact.
Will any of this work without using System.Globalization; namespace? ;)
6

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

2 Comments

This wants an IFormatProvider for its third argument.
@Nick - yeah I realized I was missing it, edited it in. Thanks.
1

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

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.