user640707
user640707

Reputation: 41

Using DateTime With input from a textbox.text

I have this code that when executed gives me 74 Days, which is correct, but the date for oldDate has to come from a TextBox. Does anyone know how to do this as the DateTime only takes three integers.

private void myButton_Click(object sender, RoutedEventArgs e)
{
     string  myDate = myTextBox.Text;

     DateTime oldDate = new DateTime(2013, 6, 5);

     DateTime newDate = DateTime.Now;

     // Difference in days, hours, and minutes.
     TimeSpan ts = oldDate - newDate;
     // Difference in days.
     int differenceInDays = ts.Days;

     differenceInDays = ts.Days;

     myTextBlock.Text = differenceInDays.ToString();        
}

Upvotes: 2

Views: 1470

Answers (2)

serene
serene

Reputation: 685

From your code you have to obtain oldDate from myTextBox, which you have stored in myDate string variable. You can convert it to datetime

oldDate=Convert.ToDateTime(myDate);

But since it might cause exception use following

`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564433

You can parse the date from the user:

string  myDate = myTextBox.Text;

DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
   // User entered invalid date - handle this
}

// oldDate is set now

That being said, depending on the UI framework, a more appropriate control (ie: the DateTimePicker from the extended WPF toolkit, etc) may be easier to use.

Upvotes: 1

Related Questions