📌  相关文章
📜  获取一个月中的星期日数 c# (1)

📅  最后修改于: 2023-12-03 15:11:50.922000             🧑  作者: Mango

获取一个月中的星期日数 c#

在编程中,我们有时需要计算一个给定月份中星期日出现的次数。本文将介绍如何使用C#来实现这一功能。

方法1:使用DateTime类

我们可以使用C#中内置的DateTime类来获取一个月份中的所有日期,然后计算其中有多少个是星期日。下面是代码示例:

using System;

public class Program
{
    public static void Main(string[] args)
    {
        int year = 2022;
        int month = 2;

        // 获取指定月份的第一天
        DateTime firstDayOfMonth = new DateTime(year, month, 1);

        // 获取指定月份的天数
        int daysInMonth = DateTime.DaysInMonth(year, month);

        int sundaysCount = 0;
        for (int i = 0; i < daysInMonth; i++)
        {
            // 获取当前日期
            DateTime currentDate = firstDayOfMonth.AddDays(i);

            // 判断当前日期是否为星期日
            if (currentDate.DayOfWeek == DayOfWeek.Sunday)
            {
                sundaysCount++;
            }
        }

        Console.WriteLine($"There are {sundaysCount} Sundays in {month}/{year}.");
    }
}
方法2:使用Linq

另外一个常用的方法是使用Linq扩展方法。Linq是C#中一种强大的查询语言,它可以帮助我们快速地对集合进行查询。下面是使用Linq计算一个月份中的星期日数的代码示例:

using System;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        int year = 2022;
        int month = 2;

        // 获取指定月份的第一天
        DateTime firstDayOfMonth = new DateTime(year, month, 1);

        // 获取指定月份的天数
        int daysInMonth = DateTime.DaysInMonth(year, month);

        // 使用Linq获取星期日的数量
        int sundaysCount = Enumerable.Range(0, daysInMonth)
                                      .Select(i => firstDayOfMonth.AddDays(i))
                                      .Count(d => d.DayOfWeek == DayOfWeek.Sunday);

        Console.WriteLine($"There are {sundaysCount} Sundays in {month}/{year}.");
    }
}

以上就是获取一个月中的星期日数的两个常用方法。希望本文能够对您有所帮助!