我只是想知道如何计算DateTime而不包括周末(目前正在建立一个图书馆系统)。图书馆在周末没有营业,这就是为什么我需要计算不包括周末的日期。 防爆。 2015年3月13日=星期五,我借了5天。所以,返回日期应该是03/20/15 =星期五(因为我没有包括周末) 你能告诉我还是给我一些想法?谢谢!
编辑:(当我键入数字时,程序突然冻结)
int days = 0;
DateTime deyt = DateTime.Now;
rd.Text = deyt.ToString("MM/dd/yy");
DateTime dt = deyt.AddDays(int.Parse(textBox3.Text));
DateTime span = deyt;
while (span < dt.AddDays(1))
{
if (span.DayOfWeek != DayOfWeek.Saturday && span.DayOfWeek != DayOfWeek.Sunday)
{
days++;
span = span.AddDays(1);
bd.Text = days.ToString("MM/dd/yy");
}
}
答案 0 :(得分:4)
如果您有日期时间列表,则可以过滤周末日期:
public static List<DateTime> GetDatesWithoutWeekends(List<DateTime> dates)
{
return
dates.Where(date => (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday))
.ToList();
}
答案 1 :(得分:1)
DateTime date = DateTime.Now // Set your Date
if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
{
//TODO
}
答案 2 :(得分:1)
有很多有效的方法可以在很长一段时间内完成此操作,但如果您的代码只处理小值,您可以使用:
static DateTime AddDaysExcludingWeekends(DateTime start, int days)
{
// Do you need this?
if (days < 0)
{
throw new ArgumentException("Not implemented yet...");
}
DateTime current = start;
for (int i = 0; i < days; days++)
{
current = current.AddDays(1);
if (current.DayOfWeek == DayOfWeek.Sunday ||
current.DayOfWeek == DayOfWeek.Saturday)
{
// Effectively force "go round again" behaviour.
i--;
}
}
return current;
}
或另一种方法:
static DateTime AddDaysExcludingWeekends(DateTime start, int days)
{
// Do you need this?
if (days < 0)
{
throw new ArgumentException("Not implemented yet...");
}
DateTime current = start;
for (int i = 0; i < days; days++)
{
// Loop at least once, and keep going until we're on
// a weekday.
do
{
current = current.AddDays(1);
}
while (current.DayOfWeek == DayOfWeek.Sunday ||
current.DayOfWeek == DayOfWeek.Saturday);
}
return current;
}
请注意,如果您传入的天数= 0,即使是在周末,也会返回原始日期。目前尚不清楚你是否想要这种行为,或者它是否应该跳到星期一。
答案 3 :(得分:0)
This is your code... Try..
int days = 0;
DateTime deyt = DateTime.Now;
DateTime dt = deyt.AddDays(int.Parse(textBox3.Text));
DateTime span = deyt;
while (span <= dt)
{
if (span.DayOfWeek != DayOfWeek.Saturday && span.DayOfWeek != DayOfWeek.Sunday)
{
days++;
bd.Text = days.ToString();
Console.WriteLine(span.ToString("MM/dd/yy"));
}
span = span.AddDays(1);
}