如何计算asp中的日期差异

时间:2015-03-07 05:01:56

标签: c#

我需要几天的日期差异。我使用TimeSpan来计算差异。但它只显示了几小时的差异。我希望在几天后显示到我的文本框中。我的代码中有什么问题。

我的代码在这里:

protected void txtDate1_TextChanged(object sender, EventArgs e)
{
    startdate = DateTime.Parse(txtDate.Text).Date;
    enddate = DateTime.Parse(txtDate1.Text).Date;
    remaindate = (enddate - startdate);
    txtdays.Text = remaindate.TotalDays.ToString();
}

1 个答案:

答案 0 :(得分:0)

这是可能的解决方案:

1。如果日期来自文本框:

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();

2。如果Datetime在代码后面动态采用:

DateTime d1=DateTime.MinValue;
DateTime d2=DateTime.MaxValue;
TimeSpan span=d2-d1;
Console.WriteLine( "There're {0} days between {1} and {2}" , span.TotalDays, d1.ToString(), d2.ToString() );

如果有帮助,请告诉我!