C#计算两个日期之间每月的天数

时间:2021-01-06 07:08:21

标签: c#

我是 C# 新手,我需要计算两个日期之间每月的天数(使用 DateTimePicker 选择)

示例: 我的开始日期是 2020 年 1 月 2 日,结束日期是 2020 年 3 月 4 日,那么最终结果应该是

Jan : 30 Feb : 29 Mar : 4

1 个答案:

答案 0 :(得分:-2)

只需使用 DateTimeTimeSpan

using System;
using System.Globalization;

namespace SO
{
    class Program
    {
        
        static void Main(string[] args)
        {
            CultureInfo culture = new CultureInfo("en-US");

            DateTime start = new DateTime(2020, 1, 2); // 2 January 2020
            DateTime end = new DateTime(2020, 3, 4); // 4 March 2020

            if (start.Year == end.Year && start.Month == end.Month) {
                var daysInSingleMonth = end.Day - start.Day;
                Console.WriteLine(start.ToString("MMM", culture) + " (Single Month): " + daysInSingleMonth.ToString("00"));
            } else {
                var daysInFirstMonth = DateTime.DaysInMonth(start.Year, start.Month) - start.Day;
                Console.WriteLine(start.ToString("MMM", culture) + " (First Month): " + daysInFirstMonth.ToString("00"));

                DateTime current = start.AddMonths(1);
                while (current <= end.AddMonths(-1))
                {
                    var daysInCurrentMonth = DateTime.DaysInMonth(current.Year, current.Month);
                    Console.WriteLine(current.ToString("MMM", culture) + ": " + daysInCurrentMonth.ToString("00")); 

                    current = current.AddMonths(1);
                }

                var daysInLastMonth = end.Day;
                Console.WriteLine(end.ToString("MMM", culture) + " (Last Month): " + daysInLastMonth.ToString("00"));
            }            
        }
    }
}

输出将是。

Jan (First Month): 29
Feb: 29
Mar (Last Month): 04

如果需要,您可以删除第一个月和最后一个月并更新格式化字符串的文化。