我有一个场景,我想通过从今天的日期减去 8 个工作日来找到日期。假设今天的日期是 04/21/10。现在我想显示日期是 04/09/10。周末应该被排除在外。
例如。 如果今天的日期是 04/21/10
减去周末: 星期六- 04/10/10 ,04/17/10 周日-04/11/10,04/18/10
输出结果为 04/09/10。
我想用 C# 来做。
任何帮助或建议都会有所帮助。
谢谢, 提交
最佳答案
显然有很多的方法可以做到这一点,但也许对生成器有一点乐趣。我使用过扩展方法,但 YMMV。因此,确定您是否需要使您的代码具有文化意识(或根据您的需要需要的任何描述符)等等
public static class DateTimeExtensions
{
public static IEnumerable<DateTime> Forwards(this DateTime dateTime)
{
return dateTime.Forwards(TimeSpan.FromDays(1));
}
public static IEnumerable<DateTime> Forwards(this DateTime dateTime, TimeSpan span)
{
while (true)
{
yield return dateTime += span;
}
}
public static IEnumerable<DateTime> Backwards(this DateTime dateTime)
{
return dateTime.Backwards(TimeSpan.FromDays(1));
}
public static IEnumerable<DateTime> Backwards(this DateTime dateTime, TimeSpan span)
{
return dateTime.Forwards(-span);
}
public static bool IsWorkingDay(this DateTime dateTime)
{
return dateTime.IsWorkingDay(Thread.CurrentThread.CurrentUICulture);
}
public static bool IsWorkingDay(this DateTime dateTime, CultureInfo culture)
{
return !dateTime.IsWeekend(culture)
&& !dateTime.IsHoliday(culture);
}
public static bool IsWeekend(this DateTime dateTime)
{
return dateTime.IsWeekend(Thread.CurrentThread.CurrentUICulture);
}
public static bool IsWeekend(this DateTime dateTime, CultureInfo culture)
{
// TOOD: Make culturally aware
return dateTime.DayOfWeek == DayOfWeek.Saturday
|| dateTime.DayOfWeek == DayOfWeek.Sunday;
}
public static bool IsHoliday(this DateTime dateTime)
{
return dateTime.IsHoliday(Thread.CurrentThread.CurrentUICulture);
}
public static bool IsHoliday(this DateTime dateTime, CultureInfo culture)
{
throw new NotImplementedException("TODO: Get some culture aware holiday data");
}
}
然后使用 DateTime 生成器为一些 LINQ 表达式提供动力:
// Display every holiday from today until the end of the year
DateTime.Today.Forwards()
.TakeWhile(date => date.Year <= DateTime.Today.Year)
.Where(date => date.IsHoliday())
.ForEach(date => Console.WriteLine(date));
你明白了
关于c# - 如何计算从今天算起的8个工作日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681787/