如何检查去年

时间:2014-01-16 10:35:15

标签: c#

我想计算去年未使用的休假日,并将其显示在网格列中。我知道我只需做一个简单的计算

像:

VacationDays - UsedVacationDays ==去年剩余的休假日

但是如何检查我是否只收到去年的数据?我知道必须有DateTime.Today.AddYears(-1)的东西,至少我认为洙..

到目前为止我的代码:

public double UnusedVacationDays
        {

            get
            {
                return (this.VacationDays - this.UsedVacationDays);
            }

        }

修改

 public double GetUsedVacation(int year)
        {
            double hours = 0;

            IEnumerable<HtVacationDay> vacationDays = this.HtVacationDays.Where(x => x.FromDate.Year == year && x.FromDate < DateTime.Today);
            foreach (HtVacationDay vacation in vacationDays)
            {
                TimeSpan span = vacation.ToDate - vacation.FromDate;
                if (span.TotalHours > 8)
                {
                    hours += span.TotalHours / 3;
                }
                else
                {
                    hours += span.TotalHours;
                }
            }

            return hours / 8;

感谢您的帮助! ^^

1 个答案:

答案 0 :(得分:0)

计算休假时间时,请使用属于您年份的日期范围:

public double GetUsedVacation(int year)
 {
    double hours = 0;

    IEnumerable<HtVacationDay> vacationDays = 
        HtVacationDays.Where(x => x.FromDate.Year == year && 
                                  x.FromDate < DateTime.Today);

    DateTime firstDayOfYear = new DateTime(year, 1, 1);
    DateTime lastDayOfYear = new DateTime(year, 12, 31);

    foreach (HtVacationDay vacation in vacationDays)
    {
        DateTime from = vacation.FromDate.Date < firstDayOfYear ?
              firstDayOfYear : vacation.FromDate;

        DateTime to = vacation.ToDate.Date > lastDayOfYear ?
              lastDayOfYear : vacation.ToDate;

        var vacationHours = (to - from).TotalHours;            

        if (vacationHours > 8)            
            hours += vacationHours / 3;            
        else            
            hours += vacationHours;            
    }

    return hours / 8;
}

另外我认为小时计算应该复杂得多。因为假期从15:00开始到第二天13:00结束,您的代码将返回22小时。除以3得到的时间少于3小时。但实际上如果我们从上午9点到下午6点有工作日,它应该给5 + 4 = 9小时的假期。