gpt4 book ai didi

c# - 如何根据同月的日期查找一个月中特定日期的第 5 天或结束日期

转载 作者:行者123 更新时间:2023-11-30 16:50:48 25 4
gpt4 key购买 nike

我一直在尝试根据同月的日期查找一个月中某一天的第 5 周日期,例如第 5 周星期一日期、第 5 周星期二日期、星期三......等等。这个日期可以属于同月的任何一周。我试过了

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。寻找一些指导注意:这里的月份会根据用户输入而改变,所以如何返回第五天的日期,如果它存在于给定的月份

最佳答案

这应该给你第 5 天(如果有的话)......

 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();

关于c# - 如何根据同月的日期查找一个月中特定日期的第 5 天或结束日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com