如何根据同一月的日期查找一个月中特定日期的第5个或结束日期 [英] How to Find 5th or ending date of a particular day in a month based on date of the same month
问题描述
我一直试图根据同月的日期来查找一个月中一天的第5周日期,例如第5周星期一日期,第5周星期二日期,星期三等.该日期可以属于同一月的任何一周.我尝试过
I have been trying to find the 5th week date of a day in a month like 5th week Monday date, 5th week Tue date, Wed... and so on based on the date from the same month. This date could belong to any week of same month. I tried like
DateTime MonthEventDate=05/01/2016; //Date format in dd/MM/yyyy format
DayOfWeek EventDay="Sunday"; //For Example i want to find 5th Sunday in January Month, but days too will change everytime based on user selection
string SelectedWeek="5"; //Here i'm getting the week in which i need to find the given date i.e, 5th Monday or Tuesday & so on
if (SelectedWeek == "5")
{
//Here i tried to add number of days to my initial day to find 5th day date, but every time its returning next month value
MonthEventDate = MonthEventDate.AddDays((EventDay < MonthEventDate.DayOfWeek ? 31 : 28) + EventDay - MonthEventDate.DayOfWeek);
}
我知道逻辑是错误的,但是我想获取一周中第5天的日期,如果不存在该天,则返回0.寻找一些指导注意:此处的月份将根据用户输入而改变,因此,如果给定月份中存在第五天的日期,该如何返回
I know the logic is wrong but i want to get date of 5th day of the week, and if that day is not present, return 0. Looking for some guidance Note: Here Month will change based on User Input, so how to return Date of fifth day, if it exist in the given month
推荐答案
这应该给您第5天(如果有的话)...
This should give you the 5th day (if there is one) ...
DateTime dayInMonth = DateTime.Now;
DayOfWeek dayToFind = DayOfWeek.Friday;
var fifth= Enumerable.Range(1, DateTime.DaysInMonth(dayInMonth.Year, dayInMonth.Month))
.Select(day => new DateTime(dayInMonth.Year, dayInMonth.Month, day))
.Where(day => day.DayOfWeek == dayToFind)
.Skip(4)
.FirstOrDefault();
这篇关于如何根据同一月的日期查找一个月中特定日期的第5个或结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!