如何使用 c# .net 2.0 获取“2013 年 4 月第一个星期三”的日期?
.net 中是否有针对此类工作的辅助方法,或者我应该编写自己的辅助方法?如果没有适合此类工作的方法,请帮助我编写自己的方法。
DateTime GetFirstXDayFromY(string dayName, DateTime targetYearMonth)
{
///???
}
public static DateTime GetFirstDay(int year, int month, DayOfWeek day)
{
DateTime result = new DateTime(year, month, 1);
while (result.DayOfWeek != day)
{
result = result.AddDays(1);
}
return result;
}
如果您使用的是 .net >= 3.5,则可以使用 Linq:
public static DateTime GetFirstDay(int year, int month, DayOfWeek dayOfWeek)
{
return Enumerable.Range(1, 7).
Select(day => new DateTime(year, month, day)).
First(dateTime => (dateTime.DayOfWeek == dayOfWeek));
}
请尝试使用以下代码片段。
// Get the Nth day of the month
private static DateTime NthOf(DateTime CurDate, int Occurrence, DayOfWeek Day)
{
var fday = new DateTime(CurDate.Year, CurDate.Month, 1);
if (Occurrence == 1)
{
for (int i = 0; i < 7; i++)
{
if (fday.DayOfWeek == Day)
{
return fday;
}
else
{
fday = fday.AddDays(1);
}
}
return fday;
}
else
{
var fOc = fday.DayOfWeek == Day ? fday : fday.AddDays(Day - fday.DayOfWeek);
if (fOc.Month < CurDate.Month) Occurrence = Occurrence + 1;
return fOc.AddDays(7 * (Occurrence - 1));
}
}
如何调用/使用它们?
NthOf(targetYearMonth, 1, DayOfWeek.Wednesday)
在@vc和@Jayesh的答案的帮助下,我想出了这个方法。非常感谢。
public static DateTime GetFirstDay(int year, int month, DayOfWeek day, int occurance)
{
DateTime result = new DateTime(year, month, 1);
int i = 0;
while (result.DayOfWeek != day || occurance != i)
{
result = result.AddDays(1);
if((result.DayOfWeek == day))
i++;
}
return result;
}
.NET Framework 可以轻松确定特定日期在一周中的第几天,并显示特定日期的本地化工作日名称。
我不喜欢对可以计算的东西使用循环。
这是我的实现:
public static DateTime GetNthDayOfWeek(int month, int year, int nth, DayOfWeek dayOfWeek)
{
System.Diagnostics.Debug.Assert(month >= 1 && month <= 12);
System.Diagnostics.Debug.Assert(nth > 0);
var firstDayOfMonth = new DateTime(year, month, 1, 0, 0, 0, DateTimeKind.Local);
var firstWeekDayBeforeFirstDayOfMonth = firstDayOfMonth.DayOfWeek == dayOfWeek
? firstDayOfMonth
: firstDayOfMonth.AddDays(dayOfWeek - firstDayOfMonth.DayOfWeek);
var weekOffset = firstWeekDayBeforeFirstDayOfMonth.Month != month ? nth : nth - 1;
return firstWeekDayBeforeFirstDayOfMonth.AddDays(7 * weekOffset);
}