计算2个日期之间的天数 [英] calculate no of days betwwn 2 dates

查看:150
本文介绍了计算2个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在开始日期文本框中选择了2011年11月10日的日期, 2011年12月10日在enddate文本框中,然后在days文本框中应显示2.但是我得到1,请帮助我.

if i select date 11/10/2011 in startdate textbox & 12/10/2011 in enddate textbox, then in days textbox it should display 2. but i am getting 1, pls help me.

DateTime startDate = Convert.ToDateTime(txtStartDate.Text);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text);

//
//if (!(endDate < startDate)) - [edit] replaced with below if
if (endDate > startDate)
{
    TimeSpan ts = endDate.Subtract(startDate);
    txtTotalDays.Text = ts.Days.ToString();
}
else
{
    Response.Write("End Date should be higher than Start Date");
}

推荐答案

我只使用TimeSpan class.
I''d just use a TimeSpan class.
TimeSpan ts = endDate.Subtract(startDate);


不,不应该.如果取两个数字,将得到相同的结果. 12-11 =1.是两个日期还是两个罐中的豆子数量都没关系.

如果您希望数字包括不完整的天数,则必须手动添加一个数字:
No, it shouldn''t. If you take any two numbers, you will get the same result. 12 - 11 = 1. It doesn''t matter if it is two dates, or the number of beans in two tins.

If you want the number to be inclusive of partial days, you will have to add the one on manually:
TimeSpan ts = endDate.Subtract(startDate);
txtTotalDays.Text = (ts.Days + 1).ToString();


今天之间的区别肯定是明天是一天
Surely the difference between today and tomorrow is one day


这篇关于计算2个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆