计算以月份分隔的两个日期之间的天数 [英] Calculate number of days between two dates separated by month

查看:125
本文介绍了计算以月份分隔的两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算两个日期之间的天数( DateTime ),但有一个扭曲。我想知道这两天的每一个月有多少天。有两种方法吗?

I need to calculate the number of days between two dates (DateTime) but with a twist. I want to know how many days fall into each of the months that the two days span. Is there an easy way two do it?

示例:

我有开始日期30/03/2011结束日期05/04/2011那么结果应该是这样的:

I have start date 30/03/2011 and end date 05/04/2011 then the result should be something like:

var result = new Dictionary<DateTime, int>
             {
                { new DateTime(2011, 3, 1), 2 },
                { new DateTime(2011, 4, 1), 5 }
             };


推荐答案

你可以这样尝试:

using System;
using System.Collections.Generic;

static class Program {

    // return dictionary tuple<year,month> -> number of days
    static Dictionary<Tuple<int, int>, int> GetNumberOfDays(DateTime start, DateTime end) {
        // assumes end > start
        Dictionary<Tuple<int, int>, int> ret = new Dictionary<Tuple<int, int>, int>();
        DateTime date = end;
        while (date > start) {
            if (date.Year == start.Year && date.Month == start.Month) {
                ret.Add(
                    Tuple.Create<int, int>(date.Year, date.Month),
                    (date - start).Days + 1);
                break;
            } else {
                ret.Add(
                    Tuple.Create<int, int>(date.Year, date.Month),
                    date.Day);
                date = new DateTime(date.Year, date.Month, 1).AddDays(-1);
            }
        }
        return ret;
    }

    static void Main(params string[] args) {
        var days = GetNumberOfDays(new DateTime(2011, 3, 1), new DateTime(2011, 4, 1));
        foreach (var m in days.Keys) {
            Console.WriteLine("{0}/{1} : {2} days", m.Item1, m.Item2, days[m]);
        }
    }

}

这篇关于计算以月份分隔的两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆