0

I have two textBox in first i have Date in this format : 2012.09.20 and in the second i have Time in this format: 15:30:00. In database i have Column name "Eventstart" type: DateTime. Now i like to take the value from two textbox and put them in something like this:

DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + Convert.ToDateTime(TextBoxTimeEnd.Text);

But give me this error : Error 2 Operator '+' cannot be applied to operands of type 'System.DateTime' and 'System.DateTime'

4 Answers 4

4

It sounds like you should be using:

DateTime date = Convert.ToDateTime(TextBoxEnd.Text);
DateTime time = Convert.ToDateTime(TextBoxTimeEnd.Text);
DateTime combined = date.Date + time.TimeOfDay;

Or you could combine the text and then parse that:

DateTime dateTime = Convert.ToDateTime(TextBoxEnd.Text + " " +
                                       TextBoxTimeEnd.Text);

I'm not sure I'd use Convert.ToDateTime at all though - if you know the exact format that the textbox will be in, you should use DateTime.TryParseExact. You should work out which culture to use in that case though. If it's a genuinely fixed precise format, CultureInfo.InvariantCulture might be appropriate. If it's a culture-specific format, then use the user's culture.

You might also want to use an alternative UI representation which doesn't use textboxes at all, which would avoid potentially troubling string conversions.

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

Comments

2

Concatenate your TextBoxes text and use DateTime.ParseExact with format "yyyy.MM.dd HH:mm:ss"

After concatenating the text you should have: "2012.09.20 15:30:00"

DateTime dt = DateTime.ParseExact(TextBoxEnd.Text + " " + TextBoxTimeEnd.Text, 
                                  "yyyy.MM.dd HH:mm:ss", 
                                  CultureInfo.InvariantCulture);

Comments

0

Have you tried something like

DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + TimeSpan.Parse(TextBoxTimeEnd.Text);

Comments

0

First concatenate both the values and then add it to a DateTime variable

example:

string str = date.Text + time.Text;  // assumed date and time are textboxes

DateTime dt=new DateTime();
DateTime.TryParse(str,dt); // returns datetime in dt if it is valid

2 Comments

Add takes a TimeSpan object, not another DateTime, for the obvious reason that adding two dates doesn't make any sense.
@verdesmarald sorry that was mistake. I thought it takes but there is no method for add datetime.

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.