如何在 c# 中表示没有 31 天的月份的日期范围

本文关键字:范围 日期 表示 | 更新日期: 2023-09-27 17:55:55

我想找到员工在一个月内请的假。该代码适用于所有日期。现在,如果我想找到员工在一月份休假,范围是:

DateTime first = Convert.ToDateTime(DateTime.Now.Month + "01" + DateTime.Now.Year);
DateTime end = Convert.ToDateTime(DateTime.Now.Month + "31" + DateTime.Now.Year);

问题是有些月份没有 31 天。有没有一种简单的方法可以让我将变量从和到范围分配。当月份是 2 月或 4 月时会给出错误,因为它们没有 31 天。

执行搜索的代码是:

returnedRows = LeaveDS.Tables["Leave"].Select("LeaveDate >= #" + first + "# AND LeaveDate <= #" + end + "#");

如何在 c# 中表示没有 31 天的月份的日期范围

你可以做这样的事情:

DateTime end = first.AddMonths(1).AddDays(-1);
DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)

它会给你一个月中的天数。

使用 DateTime.DaysInMonth(int year, int month)

        int days = DateTime.DaysInMonth(2012, 2);
        int days2 = DateTime.DaysInMonth(2011, 2);

输出:

 days = 29
 days2 = 28

您可以通过 DateTime.DaysInMonth(year,month) 获取一个月中的天数,并将其用作查询的基础。

另一种方法是使用每月的第一天,但将选择查询更改为小于结束日期。

DateTime first = Convert.ToDateTime(DateTime.Now.Month + "01" + DateTime.Now.Year);
DateTime end = first.AddMonths(1); // Becomes 01 of next month
returnedRows = LeaveDS.Tables["Leave"].Select("LeaveDate >= #" + first + "# AND LeaveDate < #" + end + "#");

有一个很好的方法可以获取一个月中的天数,它被称为DateTime.DaysInMonth

DateTime end = new DateTime(first.Year, first.Month, DateTime.DaysInMonth(first.Year, first.Month);
var enddate = DateTime.Now.AddMonths(1);
DateTime end = new DateTime(enddate.Year,enddate.Month,1);

顺便说一下,如果您使用的是 .NET 3.5 或更高版本,Linq-To-DataSet 将简化和改进代码:

int month = 2; // f.e. for february
var currentCalendar = System.Globalization.CultureInfo.CurrentCulture.Calendar;
int daysInMonth = currentCalendar.GetDaysInMonth(month);
DateTime start = new DateTime(DateTime.Now.Year, month, 1);
DateTime end = new DateTime(DateTime.Now.Year, month, daysInMonth);
var filteredRows = LeaveDS.Tables["Leave"].AsEnumerable()
    .Where(r => r.Field<DateTime>("LeaveDate").Date >= start
             && r.Field<DateTime>("LeaveDate").Date <= end );
// use ToArray for an array, CopyToDataTable for a DataTable etc.