简体   繁体   中英

how to get specific day in date range

i want to get specific day that i want in date range any idea how to do this,

how to get "Saturday" from List range : in below code

 var startDate =  dtpInsetDate.Value.ToDate();
                var endDate = dtpEndDate.Value.ToDate();
                int days = (endDate - startDate).Days + 1; // incl. endDate 
                string day = endDate.Day.ToString();
                List<DateTime> range = Enumerable.Range(0, days)
                 .Select(i => startDate.AddDays(i))
                 .ToList();
                if (day.StartsWith("Sat") == true)
                { 

                }

You can use this if you want the first Saturday in your range.

var saturday = range.FirstOrDefault(dt => dt.DayOfWeek == DayOfWeek.Saturday);

Or this if you want all saturdays in your range:

var saturday = range.Where(dt => dt.DayOfWeek == DayOfWeek.Saturday);

Use the DayOfWeek property on the DateTime Object.

        var dayList = new List<DateTime>();

        foreach(var day in dayList)
        {
            if (day.DayOfWeek == DayOfWeek.Sunday) //Sunday
            if (day.DayOfWeek == DayOfWeek.Monday) //Monday
            etc...
        }

Or Linq

        dayList.Where(x => x.DayOfWeek == DayOfWeek.Sunday).ToList();

how to get "Saturday" from List range

Based on your comment;

DateTime saturday = range.Where(d => d.DayOfWeek == DayOfWeek.Saturday).FirstOrDefault();

I assumed your range has only one Saturday, this will return it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM