简体   繁体   English

计算两个日期之间的天数的代码

[英]Code to calculate no.of days between two dates

C# Code to calculate no.of days between two dates...I have start date in one textbox and end date in another textbox and i need to get no. C#代码来计算两个日期之间的天数...我在一个文本框中有开始日期,在另一个文本框中有结束日期,我需要获取否。 of days between the two dates and to be displayed in third textbox and it should exclude holidays and weekends(saturday and sunday). 两个日期之间的天数,并显示在第三个文本框中,并且应排除假日和周末(周六和周日)。

You can parse the textbox dates to date time object and then try something on the following lines. 您可以将文本框日期解析为日期时间对象,然后在以下几行中尝试一些操作。

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);
 var dateDiff = FirstDate - SecondDate; 
 double totalDays = dateDiff.TotalDays;

if you have two dates in textboxes viz textBox1 and textBox2 如果文本框中有两个日期,即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;

Edit 编辑

If you need to do it without looping , Here is how to do it. 如果您需要不循环而执行操作,请按以下步骤操作。 .

If date difference is too large, looping may consume some amount of extra time. 如果日期差太大,则循环可能会消耗一些额外的时间。

Try this.. 尝试这个..

    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; }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM