C#代码计算两个日期之间的天数...我在一个文本框中有开始日期,在另一个文本框中有结束日期,我需要得到否。两个日期之间的天数,并显示在第三个文本框中,它应该排除假期和周末(星期六和星期日)。
答案 0 :(得分:3)
您可以解析文本框日期到日期时间对象,然后尝试以下几行。
DateTime startDate = new DateTime(2013, 03, 01);
DateTime endDate = DateTime.Today; // 12 March 2013
int totalDays = 0;
while (startDate <= endDate)
{
if (startDate.DayOfWeek == DayOfWeek.Saturday
|| startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(1);
continue;
}
startDate = startDate.AddDays(1);
totalDays++;
}
Console.WriteLine("Total days excluding weekends: {0}", totalDays);
答案 1 :(得分:2)
var dateDiff = FirstDate - SecondDate;
double totalDays = dateDiff.TotalDays;
答案 2 :(得分:1)
如果文本框中有两个日期,即textBox1和textBox2
DateTime date1= new DateTime();
DateTime date2 = new DateTime();
double days;
bool isDate1Valid =DateTime.TryParse(textBox1.Text, out date1);
bool isDate2Valid =DateTime.TryParse(textBox2.Text, out date2);
if(isDate1Valid && isDate2Valid)
days = (date1-date2).TotalDays;
修改强>
如果您需要而不循环,Here is how to do it.。
如果日期差异太大,循环可能会消耗一些额外的时间。
答案 3 :(得分:1)
试试这个..
DateTime startdate = DateTime.Parse("somedate");
DateTime enddate = DateTime.Parse("somedate");
int daycount = 0;
while (startdate < enddate)
{
startdate = startdate.AddDays(1); // Fixed
int DayNumInWeek = (int)startdate.DayOfWeek;
if (DayNumInWeek != 0)
{
if (DayNumInWeek != 6)
{ daycount += 1; }
}
}