检查范围内的任何日期是否在指定月份内

时间:2016-01-22 01:48:05

标签: c# datetime

我对最佳方法感到有点失落。假设我有以下内容:

driver.findElement(By.cssSelector("table tbody tr"));

我正在尝试创建一个检查,以查看coverageStartDate和coverageEndDate的日期范围是否在2月份。请记住,值也可能如下所示:

//Get the first and last day of the month -- ex February
int month = DateTime.ParseExact("February", "MMMM", new CultureInfo("en-US")).Month;
var now = DateTime.Now;

var firstOfMonth = new DateTime(now.Year, month, 1);
var lastOfMonth = new DateTime(now.Year, month, DateTime.DaysInMonth(now.Year, month));

var coverageStartDate = new DateTime(now.Year, 1, 1);
var coverageEndDate = new DateTime(now.Year, 2, 15);

只要覆盖范围中的单个日期开始/结束日期范围落在2月份,我就希望返回true。

1 个答案:

答案 0 :(得分:2)

使用DateTime,您可以使用> =,< =等等

采用你的代码,我会做这样的事情:

var firstOfMonth = new DateTime(now.Year, month, 1, 0, 0, 0);
var lastOfMonth = new DateTime(now.Year, month, DateTime.DaysInMonth(now.Year, month), 23, 59, 59);

var coverageStartDate = new DateTime(now.Year, 1, 1);
var coverageEndDate = new DateTime(now.Year, 2, 15);

if(coverageStartDate <= lastOfMonth && coverageEndDate >= firstOfMonth)
{
  // Do something
}

此代码不要求年份必须相同,因此覆盖时间可以跨越多年。