简体   繁体   中英

Get list of dates for first week of current month in C#

I have the below code which I am working around the list of dates for the first week in the current month.

 public static List<DateTime> GetDates(int year, int month)
{
   return Enumerable.Range(1, DateTime.DaysInMonth(year, month))  
                    .Select(day => new DateTime(year, month, day)) 
                    .ToList(); 
}

But the issue is that I have getting all the dates for the current month.

What I want to achieve is the following:

Day: SUN, MON, TUE, WED, THU, FRI, SAT
Date 1, 2, 3, 5, 6.. 

How can I achieve this in C#?

Using this:

DateTime today = DateTime.Today;
            int currentDayOfWeek = (int) today.DayOfWeek;
            DateTime sunday = today.AddDays(-currentDayOfWeek);
            DateTime monday = sunday.AddDays(1);
            // If we started on Sunday, we should actually have gone *back*
            // 6 days instead of forward 1...
            if (currentDayOfWeek == 0)
            {
                monday = monday.AddDays(-7);
            }
            var dates = Enumerable.Range(0, 6).Select(days => monday.AddDays(days)).ToList();


            foreach (var date in dates) {
            Console.WriteLine(date);
            }

I managed to get the for the current week. But how can I get the day also?

The output is:

04.05.2020 00:00:00
05.05.2020 00:00:00
06.05.2020 00:00:00
07.05.2020 00:00:00
08.05.2020 00:00:00
09.05.2020 00:00:00

I want my ouput to be:

MON - 04.05.2020 TUE - 05.05.2020

You can use Enumerable.Take to get the first week (which corresponds to the first 7 items) of the returned list.

Enumerable.Range(1, DateTime.DaysInMonth(2020, 5))
                    .Select(day => new DateTime(2020, 5, day))
                    .Take(7)
                    .ToList();

Since you've stated that the first week should actually start on monday, you can modify the query using Enumerable.SkipWhile to skip the days until you found the first correct date.

Enumerable.Range(1, DateTime.DaysInMonth(2020, 5))
                    .Select(day => new DateTime(2020, 5, day))
                    .SkipWhile(z => z.DayOfWeek != DayOfWeek.Monday)
                    .Take(7)
                    .ToList();

Regarding your comment:

Using the ddd formatter you can get the short names of the days. string shortName = DateTime.Now.ToString("ddd");

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