![](/img/trans.png)
[英]C# - Get the first day and last day of the week knowing the week number, month number and year
[英]Get first week day of specific year-month
如何使用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));
}
使用.NET Framework,可以轻松确定特定日期的星期几,并显示特定日期的本地化工作日名称。
请尝试使用以下代码段。
// 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.