C# 计算给定日期范围内的星期一数
给定一个日期范围,我需要知道有多少周一(或周二、周三等)在该范围内C# 计算给定日期范围内的星期一数,c#,datetime,date,datediff,C#,Datetime,Date,Datediff,给定一个日期范围,我需要知道有多少周一(或周二、周三等)在该范围内 我目前使用C#。任何特定语言,因此使用日期格式 如果日期表示为天数,那么两个值加上一(天)再除以7的差值就是大部分答案。如果两个结束日期都是相关日期,请添加一个 编辑:将“模7”修改为“除以7”-谢谢。这就是整数除法。添加尽可能小的数字,使第一天成为周一。减去尽可能小的数字,使最后一天成为星期一。计算以天为单位的差值并除以7。因为您使用的是C#,如果您使用的是C#3.0,那么您可以使用LINQ 假设您有一个数组/列表/IQuer
我目前使用C#。任何特定语言,因此使用日期格式 如果日期表示为天数,那么两个值加上一(天)再除以7的差值就是大部分答案。如果两个结束日期都是相关日期,请添加一个
编辑:将“模7”修改为“除以7”-谢谢。这就是整数除法。添加尽可能小的数字,使第一天成为周一。减去尽可能小的数字,使最后一天成为星期一。计算以天为单位的差值并除以7。因为您使用的是C#,如果您使用的是C#3.0,那么您可以使用LINQ 假设您有一个数组/列表/IQueryable等,其中包含日期作为日期时间类型:
DateTime[] dates = { new DateTime(2008,10,6), new DateTime(2008,10,7)}; //etc....
var mondays = dates.Where(d => d.DayOfWeek == DayOfWeek.Monday); // = {10/6/2008}
增加:
不确定是否要对它们进行分组和计数,但在LINQ中也可以这样做:
var datesgrouped = from d in dates
group d by d.DayOfWeek into grouped
select new { WeekDay = grouped.Key, Days = grouped };
foreach (var g in datesgrouped)
{
Console.Write (String.Format("{0} : {1}", g.WeekDay,g.Days.Count());
}
下面是一些伪代码:
DifferenceInDays(Start, End) / 7 // Integer division discarding remainder
+ 1 if DayOfWeek(Start) <= DayImLookingFor
+ 1 if DayOfWeek(End) >= DayImLookingFor
- 1
差分日(开始、结束)/7//整数除法丢弃余数
+1如果DayOfWeek(开始)=DayImLooking查找
- 1
其中DifferenceInDays
以天为单位返回End-Start
,而DayOfWeek
以整数形式返回一周中的某一天。只要映射是递增的并且与dayimlookingfook
匹配,那么DayOfWeek
使用的映射实际上并不重要
请注意,此算法假定日期范围包含在内。如果End
不应该是范围的一部分,则必须稍微调整算法
翻译成C#是留给读者的一个练习。看看计算星期几的不同算法很有趣,@Gabe Hollombe在这个主题上指向WP是一个很好的想法(我记得大约二十年前在COBOL中实现过),但是,当人们问现在几点的时候,他们会给他们一个时钟的蓝图 在C#中:
private int CountMondays(日期时间开始日期,日期时间结束日期)
{
int mondayCount=0;
对于(日期时间dt=startDate;dt
当然,这不会计算“Mondayness”的结束日期,因此如果需要,请对for循环进行计算
dt < endDate.AddDays(1.0)
dt
将日期转换为朱利安日,然后做一点数学运算。由于星期一是零mod 7,您可以这样计算:
JD1=JulianDayOf(the_first_date)
JD2=JulianDayOf(the_second_date)
Round JD1 up to nearest multiple of 7
Round JD2 up to nearest multiple of 7
d = JD2-JD1
nMondays = (JD2-JD1+7)/7 # integer divide
我在写报告时也遇到了类似的问题。我需要两个日期之间的工作日数。
public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)
{
var selectedDates = new List<DateTime>();
if (startDate >= endDate)
return selectedDates; //No days to return
if (daysToCheck == null || daysToCheck.Count == 0)
return selectedDates; //No days to select
try
{
//Get the total number of days between the two dates
var totalDays = (int)endDate.Subtract(startDate).TotalDays;
//So.. we're creating a list of all dates between the two dates:
var allDatesQry = from d in Enumerable.Range(1, totalDays)
select new DateTime(
startDate.AddDays(d).Year,
startDate.AddDays(d).Month,
startDate.AddDays(d).Day);
//And extracting those weekdays we explicitly wanted to return
var selectedDatesQry = from d in allDatesQry
where daysToCheck.Contains(d.DayOfWeek)
select d;
//Copying the IEnumerable to a List
selectedDates = selectedDatesQry.ToList();
}
catch (Exception ex)
{
//Log error
//...
//And re-throw
throw;
}
return selectedDates;
}
我本可以循环计算日期,但我的离散数学训练不允许我这样做。下面是我在VBA中编写的一个函数,用于获取两个日期之间的工作日数。我相信.net在工作日也有类似的功能
1
2 ' WorkDays
3 ' returns the number of working days between two dates
4 Public Function WorkDays(ByVal dtBegin As Date, ByVal dtEnd As Date) As Long
5
6 Dim dtFirstSunday As Date
7 Dim dtLastSaturday As Date
8 Dim lngWorkDays As Long
9
10 ' get first sunday in range
11 dtFirstSunday = dtBegin + ((8 - Weekday(dtBegin)) Mod 7)
12
13 ' get last saturday in range
14 dtLastSaturday = dtEnd - (Weekday(dtEnd) Mod 7)
15
16 ' get work days between first sunday and last saturday
17 lngWorkDays = (((dtLastSaturday - dtFirstSunday) + 1) / 7) * 5
18
19 ' if first sunday is not begin date
20 If dtFirstSunday <> dtBegin Then
21
22 ' assume first sunday is after begin date
23 ' add workdays from begin date to first sunday
24 lngWorkDays = lngWorkDays + (7 - Weekday(dtBegin))
25
26 End If
27
28 ' if last saturday is not end date
29 If dtLastSaturday <> dtEnd Then
30
31 ' assume last saturday is before end date
32 ' add workdays from last saturday to end date
33 lngWorkDays = lngWorkDays + (Weekday(dtEnd) - 1)
34
35 End If
36
37 ' return working days
38 WorkDays = lngWorkDays
39
40 End Function
public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)
{
var selectedDates = new List<DateTime>();
if (startDate >= endDate)
return selectedDates; //No days to return
if (daysToCheck == null || daysToCheck.Count == 0)
return selectedDates; //No days to select
try
{
//Get the total number of days between the two dates
var totalDays = (int)endDate.Subtract(startDate).TotalDays;
//So.. we're creating a list of all dates between the two dates:
var allDatesQry = from d in Enumerable.Range(1, totalDays)
select new DateTime(
startDate.AddDays(d).Year,
startDate.AddDays(d).Month,
startDate.AddDays(d).Day);
//And extracting those weekdays we explicitly wanted to return
var selectedDatesQry = from d in allDatesQry
where daysToCheck.Contains(d.DayOfWeek)
select d;
//Copying the IEnumerable to a List
selectedDates = selectedDatesQry.ToList();
}
catch (Exception ex)
{
//Log error
//...
//And re-throw
throw;
}
return selectedDates;
}
1
两个工作日
3'返回两个日期之间的工作日数
public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)
{
var selectedDates = new List<DateTime>();
if (startDate >= endDate)
return selectedDates; //No days to return
if (daysToCheck == null || daysToCheck.Count == 0)
return selectedDates; //No days to select
try
{
//Get the total number of days between the two dates
var totalDays = (int)endDate.Subtract(startDate).TotalDays;
//So.. we're creating a list of all dates between the two dates:
var allDatesQry = from d in Enumerable.Range(1, totalDays)
select new DateTime(
startDate.AddDays(d).Year,
startDate.AddDays(d).Month,
startDate.AddDays(d).Day);
//And extracting those weekdays we explicitly wanted to return
var selectedDatesQry = from d in allDatesQry
where daysToCheck.Contains(d.DayOfWeek)
select d;
//Copying the IEnumerable to a List
selectedDates = selectedDatesQry.ToList();
}
catch (Exception ex)
{
//Log error
//...
//And re-throw
throw;
}
return selectedDates;
}
4个公共职能工作日(ByVal dtBegin As Date,ByVal dtEnd As Date)
5.
6.第一个星期日为日期
上周六7点作为日期
8个工作日长
9
10'获得射程中的第一个星期日
11 dtFirstSunday=dtBegin+((8-工作日(dtBegin))Mod 7)
12
13'上周六进入射程
14 dtLastSaturday=dtEnd-(工作日(dtEnd)Mod 7)
15
在第一个星期日和上个星期六之间有16个工作日
17个工作日=((上周六-上周日)+1)/7)*5
18
19'如果第一个星期日不是开始日期
20如果dtFirstSunday dtBegin然后
21
22'假设第一个星期日在开始日期之后
23'将工作日从开始日期添加到第一个星期日
24个工作日=工作日+(7个工作日(dtBegin))
25
26如果结束
27
28'如果上周六不是结束日期
29如果最后一个星期六结束,那么
30
31'假设上周六在结束日期之前
32'添加从上周六到结束日期的工作日
33 lngWorkDays=lngWorkDays+(工作日(dtEnd)-1)
34
35如果结束
36
37'返回工作日
38个工作日=1个工作日
39
40端功能
试试这个:
static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
TimeSpan ts = end - start; // Total duration
int count = (int)Math.Floor(ts.TotalDays / 7); // Number of whole weeks
int remainder = (int)(ts.TotalDays % 7); // Number of remaining days
int sinceLastDay = (int)(end.DayOfWeek - day); // Number of days since last [day]
if (sinceLastDay < 0) sinceLastDay += 7; // Adjust for negative days since last [day]
// If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.
if (remainder >= sinceLastDay) count++;
return count;
}
static int CountDays(DayOfWeek天、DateTime开始、DateTime结束)
{
TimeSpan ts=end-start;//总持续时间
int count=(int)Math.Floor(ts.TotalDays/7);//整周数
剩余天数=(int)(ts.TotalDays%7);//剩余天数
int sincellastday=(int)(end.DayOfWeek-day);//自上一个[天]起的天数
如果(SincellastDay<0)SincellastDay+=7;//调整自上一[天]起的负天数
//如果超过偶数周的天数大于或等于自上一[天]起的天数,则也要计算这一天。
如果(余数>=sincellastday)计数++;
返回计数;
}
我今天也有同样的需要。我从cjm函数开始,因为我不理解JonB函数,而且Cyberherbalist函数不是线性的
我必须纠正
DifferenceInDays(Start, End) / 7 // Integer division discarding remainder
+ 1 if DayOfWeek(Start) <= DayImLookingFor
+ 1 if DayOfWeek(End) >= DayImLookingFor
- 1
使用between函数返回true,如果从开始日开始,我们在结束日之前首先遇到dayimlookingfook
我通过计算从startDay到其他两天的天数来完成Interval函数:
private int CountDays(DateTime start, DateTime end, DayOfWeek selectedDay)
{
if (start.Date > end.Date)
{
return 0;
}
int totalDays = (int)end.Date.Subtract(start.Date).TotalDays;
DayOfWeek startDay = start.DayOfWeek;
DayOfWeek endDay = end.DayOfWeek;
///look if endDay appears before or after the selectedDay when we start from startDay.
int startToEnd = (int)endDay - (int)startDay;
if (startToEnd < 0)
{
startToEnd += 7;
}
int startToSelected = (int)selectedDay - (int)startDay;
if (startToSelected < 0)
{
startToSelected += 7;
}
bool isSelectedBetweenStartAndEnd = startToEnd >= startToSelected;
if (isSelectedBetweenStartAndEnd)
{
return totalDays / 7 + 1;
}
else
{
return totalDays / 7;
}
}
private int CountDays(日期时间开始、日期时间结束、选择的星期几)
{
如果(开始日期>结束日期)
{
返回0;
}
int totalDays=(int)end.Date.Subtract(start.Date).totalDays;
DayOfWeek startDay=start.DayOfWeek;
DayOfWeek endDay=end.DayOfWeek;
///当我们从startDay开始时,查看endDay是在所选日期之前还是之后出现。
int startToEnd=(int)endDay-(int)startDay;
如果(起始端<0)
public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)
{
var selectedDates = new List<DateTime>();
if (startDate >= endDate)
return selectedDates; //No days to return
if (daysToCheck == null || daysToCheck.Count == 0)
return selectedDates; //No days to select
try
{
//Get the total number of days between the two dates
var totalDays = (int)endDate.Subtract(startDate).TotalDays;
//So.. we're creating a list of all dates between the two dates:
var allDatesQry = from d in Enumerable.Range(1, totalDays)
select new DateTime(
startDate.AddDays(d).Year,
startDate.AddDays(d).Month,
startDate.AddDays(d).Day);
//And extracting those weekdays we explicitly wanted to return
var selectedDatesQry = from d in allDatesQry
where daysToCheck.Contains(d.DayOfWeek)
select d;
//Copying the IEnumerable to a List
selectedDates = selectedDatesQry.ToList();
}
catch (Exception ex)
{
//Log error
//...
//And re-throw
throw;
}
return selectedDates;
}
[TestMethod]
public void ShouldFindFridaysInTimeSpan()
{
//reference: http://stackoverflow.com/questions/248273/count-number-of-mondays-in-a-given-date-range
var spanOfSixtyDays = new TimeSpan(60, 0, 0, 0);
var setOfDates = new List<DateTime>(spanOfSixtyDays.Days);
var now = DateTime.Now;
for(int i = 0; i < spanOfSixtyDays.Days; i++)
{
setOfDates.Add(now.AddDays(i));
}
Assert.IsTrue(setOfDates.Count == 60,
"The expected number of days is not here.");
var fridays = setOfDates.Where(i => i.DayOfWeek == DayOfWeek.Friday);
Assert.IsTrue(fridays.Count() > 0,
"The expected Friday days are not here.");
Assert.IsTrue(fridays.First() == setOfDates.First(i => i.DayOfWeek == DayOfWeek.Friday),
"The expected first Friday day is not here.");
Assert.IsTrue(fridays.Last() == setOfDates.Last(i => i.DayOfWeek == DayOfWeek.Friday),
"The expected last Friday day is not here.");
}
int[] CountDays(DateTime firstDate, DateTime lastDate)
{
var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;
var weeks = (int)Math.Floor(totalDays / 7);
var result = Enumerable.Repeat<int>(weeks, 7).ToArray();
if (totalDays % 7 != 0)
{
int firstDayOfWeek = (int)firstDate.DayOfWeek;
int lastDayOfWeek = (int)lastDate.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)
result[dayOfWeek % 7]++;
}
return result;
}
public static Dictionary<DayOfWeek, int> TotalDaysOfWeeks(this DateTime firstDate, DateTime lastDate)
{
var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;
var weeks = (int)Math.Floor(totalDays / 7);
var resultArray = Enumerable.Repeat<int>(weeks, 7).ToArray();
if (totalDays % 7 != 0)
{
int firstDayOfWeek = (int)firstDate.DayOfWeek;
int lastDayOfWeek = (int)lastDate.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)
resultArray[dayOfWeek % 7]++;
}
var result = new Dictionary<DayOfWeek, int>();
for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++)
result[(DayOfWeek)dayOfWeek] = resultArray[dayOfWeek];
return result;
}
private int CountDays(DayOfWeek day, DateTime startDate, DateTime endDate)
{
int dayCount = 0;
for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))
{
if (dt.DayOfWeek == day)
{
dayCount++;
}
}
return dayCount;
}
int Days = CountDays(DayOfWeek.Friday, Convert.ToDateTime("2019-07-04"),
Convert.ToDateTime("2019-07-27")).ToString();