Reputation: 285
I have two textboxes : TextBox1 and TextBox2 both have date.
I want to get date difference in third textbox, that is TextBox3.
My code is:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) - Convert.ToInt32(TextBox2.Text)).ToString());
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) - Convert.ToInt32(TextBox2.Text)).ToString());
}
Upvotes: 0
Views: 2578
Reputation: 56697
Convert both input values to DateTime
, as in
DateTime dt1 = DateTime.Parse(TextBox1.Text);
DateTime dt2 = DateTime.Parse(TextBox2.Text);
Then, subtract both to get a TimeSpan
object:
TimeSpan ts = dt1 - dt2;
Then you can use the properties of ts
to set the value of the third text box:
TextBox3.Text = ts.TotalDays.ToString();
I assume here that valid dates are input into both text boxes, otherwise you'll get an exception in the first line above. You can alternatively look into the ParseExact
or TryParse/TryParseExact
methods provided by the DateTime
class.
Upvotes: 3
Reputation: 3661
DateTime d1 = TextBox1.Text!=string.Empty?Convert.ToDateTime(TextBox1.Text): DateTime.MinValue;
DateTime d2 = TextBox2.Text!=string.Empty?Convert.ToDateTime(TextBox2.Text):DateTime.MinValue;
TimeSpan tspan= d2-d1;
TextBox3.Text = tspan.TotalDays.ToString();
Upvotes: 2
Reputation: 903
Try like this
DateTime d1 = Convert.ToDateTime(TextBox1.Text);
DateTime d2 = Convert.ToDateTime(TextBox2.Text);
TimeSpan span = d2-d1;
TextBox3.Text = span.TotalDays.ToString();
Upvotes: 0