Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,817 answers

573 users

How to calculate the number of weekdays in the current year with C#

2 Answers

0 votes
using System;

class WeekdayCalculator
{
    static void Main()
    {
        int year = DateTime.Now.Year;
        int weekdayCount = CountWeekdaysInYear(year);
        
        Console.WriteLine($"Number of weekdays in {year}: {weekdayCount}");
    }

    static int CountWeekdaysInYear(int year)
    {
        int weekdayCount = 0;

        for (DateTime date = new DateTime(year, 1, 1); date.Year == year; date = date.AddDays(1)) {
            if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday) {
                weekdayCount++;
            }
        }

        return weekdayCount;
    }
}


/*
run:

Number of weekdays in 2025: 261

*/

 



answered Feb 17, 2025 by avibootz
0 votes
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int year = DateTime.Now.Year;
        int weekdayCount = CountWeekdaysInYear(year);
        
        Console.WriteLine($"Number of weekdays in {year}: {weekdayCount}");
    }

    static int CountWeekdaysInYear(int year) {
        int weekdayCount = 0;

        DateTime startDate = new DateTime(year, 1, 1);
        DateTime endDate = new DateTime(year, 12, 31);

        return Enumerable.Range(0, (endDate - startDate).Days + 1)
                         .Select(offset => startDate.AddDays(offset))
                         .Count(date => date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday);
    }
}



/*
run:

Number of weekdays in 2025: 261

*/

 



answered Feb 17, 2025 by avibootz

Related questions

1 answer 110 views
1 answer 67 views
1 answer 68 views
2 answers 67 views
1 answer 57 views
1 answer 68 views
...