计算业务/工作日C#

时间:2015-08-11 09:25:59

标签: javascript c#

我想知道在此网格中选择日期的工作日。我尝试了有效的JavaScript代码,但在C#中使用它时遇到了一些困难。

enter image description here

     string startdate, enddate;
        startdate = "";
        enddate = "";

        foreach (GridViewRow row in DateGrid.Rows) 
        {

            if (row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkRow = (row.Cells[0].FindControl("DateChBox") as CheckBox);
                if (chkRow.Checked)
                {
                    startdate = row.Cells[2].Text;
                    enddate = row.Cells[3].Text;

     // Validate input
    if (enddate < startdate)
    return 0;

// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startdate.setHours(0, 0, 0, 1);  // Start just after midnight  --> how to do this in c#?
enddate.setHours(23, 59, 59, 999);  // End just before midnight --> how to do this in c#?
var diff = enddate - startdate;  // Milliseconds between datetime objects    
var days = Math.Ceiling(diff / millisecondsPerDay);

// Subtract two weekend days for every week in between
var weeks = Math.Floor(days / 7);
days = days - (weeks * 2);

//// Handle special cases  --> this is not necessary because I choose the date
//var startDay = startdate.getDay(); 
//var endDay = enddate.getDay();

// Remove weekend not previously removed.   
if (startDay - endDay > 1)         
    days = days - 2;      

// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
    days = days - 1;  
}

// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
    days = days - 1;
}

如果有可能,我需要一些帮助才能在C#中使用它。

2 个答案:

答案 0 :(得分:2)

首先,您将dateformat中的日期转换为从startdate到endday的循环

那么你可以像这样使用

 if (!(toValidate.DayOfWeek == DayOfWeek.Sunday || toValidate.DayOfWeek == DayOfWeek.Saturday))
            {
                // do your logic 
            }

<强>更新

          int countWorkingDays= 0;
          string startdate1 = "2014/04/28";
          string  enddate1 ="2014/09/12";

            DateTime startdate= DateTime.ParseExact(startdate1, "yyyy/MM/dd",System.Globalization.CultureInfo.InvariantCulture);
            DateTime enddate= DateTime.ParseExact(enddate1, "yyyy/MM/dd",System.Globalization.CultureInfo.InvariantCulture);
            DateTime date =startdate;
            while (date<= enddate)
            {
                if (!(date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday))
                {
                    countWorkingDays++;
                }
                date= date.AddDays(1);  
            }
            Console.WriteLine("WorkingDays " +countWorkingDays);

答案 1 :(得分:0)

for (DateTime date = Start_Date; date <= End_Date; date = date.AddDays(1))
    {
        if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
        {
            yield return date;
        }
    }

从日期范围中删除周末。