任何人都可以帮助我,我如何使用C#计算每两周(14天)的逻辑?例如,按照2月的顺序顺序开始14天
我的逻辑不适用于14天的显示,因为2月15日将来14天添加,它将显示“First14days”日期2016年2月29日,这是错误的。
这是C#logic
Day.Days value are Monday, Thursday, Friday etc..
foreach (var Day in day)
{
Example Day.Days = Monday
Int 14days = (((int)Enum.Parse(typeof(DayOfWeek), Day.Days) - (int)today.DayOfWeek + 14) % 7);
DateTime First14days = today.AddDays(14days);
}
答案 0 :(得分:8)
只需将TimeSpan.FromDays(14)
添加到任何日期即可进一步了解
DateTime startDate = DateTime.Now;
TimeSpan fortnight = TimeSpan.FromDays(14);
for (int i = 0; i < 6; i++)
{
startDate += fortnight;
Console.WriteLine($"Date for fortnight {i}: {startDate:D}");
}
答案 1 :(得分:4)
如果我理解您的问题,那么此代码将适用于您。
DateTime time = DateTime.Now;
DateTime anotherTime = DateTime.Now;
var allTimes = new HashSet<DateTime>();
for (int i = 0; i < 6; i++)
{
anotherTime = time.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
// or with your example is possible to like this code.
foreach (var Day in day)
{
anotherTime = Day.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
首先创建两个DataTime对象。然后foreach几次,并在for set语句集anotherTime = time.AddDays(14)
之后设置time = anotherTime
。
//Output:
//Saturday, February 27, 2016
//Saturday, March 12, 2016
//Saturday, March 26, 2016
//Saturday, April 09, 2016
//Saturday, April 23, 2016
//Saturday, May 07, 2016
修改强>
我创建了HashSet,您可以在其中保存所有日期时间。
答案 2 :(得分:1)
所以,这就是你的一体化解决方案:
// determine the date of next given weekday
DateTime date = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);
// create a list and add the start date (if you want)
List<DateTime> fortnights = new List<DateTime>() { date };
// add as many "fortnights" as you like (e.g. 5)
for (int i = 0; i < 5; i++)
{
date = date.Add(TimeSpan.FromDays(14));
fortnights.Add(date);
}
// use your list (here: just for printing the list in a console app)
foreach (DateTime d in fortnights)
{
Console.WriteLine(d.ToLongDateString());
}
获取下一个工作日的方法,来自: https://stackoverflow.com/a/6346190/2019384
public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}