如何获得给定月份的每个“星期一”日?
一个例子;
输入:11.July.2017(11.07.2017)
产出:(3,10,17,24,31)
星期一3.7.2017
星期一10.7.2017
17.7.2017周一
星期一24.7.2017
31.7.2017
我可以获得给定月份的天数(2017年7月,这是31天)。然后编写一个迭代(对于循环a.e。)如果dayOfWeek等于星期一,则添加到列表中。但这不是好代码,因为for循环将工作31次。应该有一个更好的算法来存档目标。
我正在使用C#.net framework 4.6
更新
感谢所有人的帮助,经过一些答案我到目前为止;我用简单的方法测试了所有代码。脏基准代码,以找到更快的算法。
这是我的基准代码;
using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Columns;
using BenchmarkDotNet.Attributes.Jobs;
using BenchmarkDotNet.Engines;
using X.Core.Helpers;
namespace X.ConsoleBenchmark
{
[SimpleJob(RunStrategy.ColdStart, targetCount: 5)]
[MinColumn, MaxColumn, MeanColumn, MedianColumn]
public class LoopTest
{
[Benchmark]
public void CalculateNextSalaryDateWithLoopAllDays()
{
DateTime date = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
List<DateTime> allXDaysInMonth = date.GetAllXDaysInMonthWithLoopAllDays(DayOfWeek.Tuesday);
if (allXDaysInMonth != null && allXDaysInMonth.FirstOrDefault().Day != 4)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
[Benchmark]
public void CalculateNextSalaryDate()
{
DateTime date = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
List<DateTime> allXDaysInMonth = date.GetAllXDaysInMonth(DayOfWeek.Tuesday);
if (allXDaysInMonth != null && allXDaysInMonth.FirstOrDefault().Day != 4)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
[Benchmark]
public void Maccettura_GetAllDayOfWeekPerMonth()
{
DateTime exampleDate = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
var date = new DateTime(exampleDate.Year, exampleDate.Month, 1);
if (date.DayOfWeek != DayOfWeek.Thursday)
{
int daysUntilDayOfWeek = ((int)DayOfWeek.Thursday - (int)date.DayOfWeek + 7) % 7;
date = date.AddDays(daysUntilDayOfWeek);
}
List<DateTime> days = new List<DateTime>();
while (date.Month == exampleDate.Month)
{
days.Add(date);
date = date.AddDays(7);
}
if (days.FirstOrDefault().Day != 6)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
[Benchmark]
public void ScottHannen_GetWeekdaysForMonth()
{
DateTime exampleDate = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
IEnumerable<DateTime> days = ScottHannen_GetDaysInMonth(exampleDate).Where(day => day.DayOfWeek == DayOfWeek.Thursday);
if (days.FirstOrDefault().Day != 6)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
private IEnumerable<DateTime> ScottHannen_GetDaysInMonth(DateTime date)
{
var dateLoop = new DateTime(date.Year, date.Month, 1);
while (dateLoop.Month == date.Month)
{
yield return dateLoop;
dateLoop = dateLoop.AddDays(1);
}
}
[Benchmark]
public void Trioj_GetWeekdaysForMonth()
{
DateTime exampleDate = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
IEnumerable<DateTime> days = Trioj_GetDatesInMonthByWeekday(exampleDate, DayOfWeek.Thursday);
if (days.FirstOrDefault().Day != 6)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
private List<DateTime> Trioj_GetDatesInMonthByWeekday(DateTime date, DayOfWeek dayOfWeek)
{
// We know the first of the month falls on, well, the first.
var first = new DateTime(date.Year, date.Month, 1);
int daysInMonth = DateTime.DaysInMonth(date.Year, date.Month);
// Find the first day of the week that matches the requested day of week.
if (first.DayOfWeek != dayOfWeek)
{
first = first.AddDays(((((int)dayOfWeek - (int)first.DayOfWeek) + 7) % 7));
}
// A weekday in a 31 day month will only occur five times if it is one of the first three weekdays.
// A weekday in a 30 day month will only occur five times if it is one of the first two weekdays.
// A weekday in February will only occur five times if it is the first weekday and it is a leap year.
// Incidentally, this means that if we subtract the day of the first occurrence of our weekday from the
// days in month, then if that results in an integer greater than 27, there will be 5 occurrences.
int maxOccurrences = (daysInMonth - first.Day) > 27 ? 5 : 4;
var list = new List<DateTime>(maxOccurrences);
for (int i = 0; i < maxOccurrences; i++)
{
list.Add(new DateTime(first.Year, first.Month, (first.Day + (7 * i))));
}
return list;
}
[Benchmark]
public void Jonathan_GetWeekdaysForMonth()
{
DateTime exampleDate = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
IEnumerable<DateTime> days = Jonathan_AllDatesInMonth(exampleDate.Year, exampleDate.Month).Where(x => x.DayOfWeek == DayOfWeek.Thursday);
if (days.FirstOrDefault().Day != 6)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
private static IEnumerable<DateTime> Jonathan_AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
[Benchmark]
public void Swatsonpicken_GetWeekdaysForMonth()
{
DateTime exampleDate = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
IEnumerable<DateTime> days = Swatsonpicken_GetDaysOfWeek(exampleDate, DayOfWeek.Thursday);
if (days.FirstOrDefault().Day != 6)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
private static IEnumerable<DateTime> Swatsonpicken_GetDaysOfWeek(DateTime startDate, DayOfWeek desiredDayOfWeek)
{
var daysOfWeek = new List<DateTime>();
var workingDate = new DateTime(startDate.Year, startDate.Month, 1);
var offset = ((int)desiredDayOfWeek - (int)workingDate.DayOfWeek + 7) % 7;
// Jump to the first desired day of week.
workingDate = workingDate.AddDays(offset);
do
{
daysOfWeek.Add(workingDate);
// Jump forward seven days to get the next desired day of week.
workingDate = workingDate.AddDays(7);
} while (workingDate.Month == startDate.Month);
return daysOfWeek;
}
[Benchmark]
public void AliaksandrHmyrak_GetWeekdaysForMonth()
{
DateTime exampleDate = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
IEnumerable<DateTime> days = AliaksandrHmyrak_GetDaysOfWeek(exampleDate, DayOfWeek.Thursday);
if (days.FirstOrDefault().Day != 6)
{
throw new ApplicationException("Calculate method has errors.");
}
}
}
private static List<DateTime> AliaksandrHmyrak_GetDaysOfWeek(DateTime date, DayOfWeek dayOfWeek)
{
var daysInMonth = DateTime.DaysInMonth(date.Year, date.Month);
var i = 1;
List<DateTime> result = new List<DateTime>(5);
do
{
var testDate = new DateTime(date.Year, date.Month, i);
if (testDate.DayOfWeek == dayOfWeek)
{
result.Add(testDate);
i += 7;
}
else
{
i++;
}
} while (i <= daysInMonth);
return result;
}
}
}
如果你想要,我可以删除任何代码和图片名称 我标记了乔纳森的回答。简单,干净,快捷(有趣)。
答案 0 :(得分:5)
其他答案有效,但我更愿意使用How to add run-time processing of @NotNull annotation中的Jon Skeet的AllDaysInMonth函数
public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
然后你可以像这样调用LINQ:
var mondays = AllDatesInMonth(2017, 7).Where(i => i.DayOfWeek == DayOfWeek.Monday);
但我想这取决于你要使用它的次数,不管它是否值得分成一个单独的功能。
答案 1 :(得分:1)
尝试这样的事情:
public static IEnumerable<DateTime> GetAllDayOfWeekPerMonth(int month, int year, DayOfWeek dayOfWeek)
{
var date = new DateTime(year, month, 1);
if(date.DayOfWeek != dayOfWeek)
{
int daysUntilDayOfWeek = ((int) dayOfWeek - (int) date.DayOfWeek + 7) % 7;
date = date.AddDays(daysUntilDayOfWeek);
}
List<DateTime> days = new List<DateTime>();
while(date.Month == month)
{
days.Add(date);
date = date.AddDays(7);
}
return days;
}
演示小提琴here
答案 2 :(得分:1)
非科学地,在几千次迭代检查中,在两年的时间内检查某个工作日的随机月份会更快一点。
差异很小。它的毫秒数。所以我做任何更容易阅读的事情。我发现这更容易阅读,但在另一个答案中,功能名称使其足够清晰。如果功能名称清晰且单元测试过,那么我就不会将毛发分开。
public class WeekdaysByMonth
{
public IEnumerable<DateTime> GetWeekdaysForMonth(DateTime month, DayOfWeek weekDay)
{
return GetDaysInMonth(month).Where(day => day.DayOfWeek == weekDay);
}
private IEnumerable<DateTime> GetDaysInMonth(DateTime date)
{
var dateLoop = new DateTime(date.Year,date.Month,1);
while (dateLoop.Month == date.Month)
{
yield return dateLoop;
dateLoop = dateLoop.AddDays(1);
}
}
}
答案 3 :(得分:0)
就是这样:
private static List<DateTime> GetDaysOfWeek(DateTime date, DayOfWeek dayOfWeek)
{
var daysInMonth = DateTime.DaysInMonth(date.Year, date.Month);
var i = 1;
List<DateTime> result = new List<DateTime>(5);
do
{
var testDate = new DateTime(date.Year, date.Month, i);
if (testDate.DayOfWeek == dayOfWeek)
{
result.Add(testDate);
i += 7;
}
else
{
i++;
}
} while (i <= daysInMonth);
return result;
}
答案 4 :(得分:0)
我的版本实现了相同的结果但是通过计算从月的第一天到第一次出现的期望的偏移,避免从月的第一个到第一个星期一(或者您想要的任何一天)的循环一天。
public static IEnumerable<DateTime> GetDaysOfWeek(DateTime startDate, DayOfWeek desiredDayOfWeek)
{
var daysOfWeek = new List<DateTime>();
var workingDate = new DateTime(startDate.Year, startDate.Month, 1);
var offset = ((int)desiredDayOfWeek - (int)workingDate.DayOfWeek + 7) % 7;
// Jump to the first desired day of week.
workingDate = workingDate.AddDays(offset);
do
{
daysOfWeek.Add(workingDate);
// Jump forward seven days to get the next desired day of week.
workingDate = workingDate.AddDays(7);
} while (workingDate.Month == startDate.Month);
return daysOfWeek;
}
要解决OP问题,你可以这样称呼这个方法:
var mondays = GetDaysOfWeek(DateTime.Today, DayOfWeek.Monday);
答案 5 :(得分:0)
您可以在技术上解决整个问题,而无需在您自己的代码中进行迭代,只输入除输入之外的两条信息:第一天的月份和月份的天数。不过,我在答案中选择了一个小循环。
public List<DateTime> GetDatesInMonthByWeekday(DateTime date, DayOfWeek dayOfWeek) {
// We know the first of the month falls on, well, the first.
var first = new DateTime(date.Year, date.Month, 1);
int daysInMonth = DateTime.DaysInMonth(date.Year, date.Month);
// Find the first day of the week that matches the requested day of week.
if (first.DayOfWeek != dayOfWeek) {
first = first.AddDays(((((int)dayOfWeek - (int)first.DayOfWeek) + 7) % 7));
}
// A weekday in a 31 day month will only occur five times if it is one of the first three weekdays.
// A weekday in a 30 day month will only occur five times if it is one of the first two weekdays.
// A weekday in February will only occur five times if it is the first weekday and it is a leap year.
// Incidentally, this means that if we subtract the day of the first occurrence of our weekday from the
// days in month, then if that results in an integer greater than 27, there will be 5 occurrences.
int maxOccurrences = (daysInMonth - first.Day) > 27 ? 5 : 4;
var list = new List<DateTime>(maxOccurrences);
for (int i = 0; i < maxOccurrences; i++) {
list.Add(new DateTime(first.Year, first.Month, (first.Day + (7 * i))));
}
return list;
}