簡體   English   中英

計算以月份分隔的兩個日期之間的天數

[英]Calculate number of days between two dates separated by month

我需要計算兩個日期 ( DateTime ) 之間的天數,但有一點需要注意。 我想知道這兩天跨越的每個月有多少天。 有沒有簡單的方法二呢?

例子:

我有開始日期 30/03/2011 和結束日期 05/04/2011 那么結果應該是這樣的:

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]);
        }
    }

}

關於如何使用內置 DateTime.DaysInMonth 方法准確獲取 2 個日期之間的總月數和總天數的小例子,該方法為我們提供了每個月的天數,因此我們可以獲得 100% 的准確度。

DateTime date1 = DateTime.Now.AddDays(60);
DateTime date2 = DateTime.Now;
TimeSpan ts = date1 - date2;
int totalDays = int.Parse(ts.TotalDays.ToString("0"));
int totalMonths = Math.Abs((date1.Month - date2.Month) + 12 * (date1.Year - date2.Year));
int months = 0;
int days = 0;
int totalDaysInMonths = 0;
for (int i = totalMonths; i > 0; i--)
{
    int month = date2.Month + i;
    int year = date1.Year;
    if (month > 12)
    {
        year++;
        int newMonth = month - 12;
        month = newMonth;
    }

    totalDaysInMonths = totalDaysInMonths + DateTime.DaysInMonth(year, month);
}

if (totalDays > totalDaysInMonths)
{
    months = totalMonths - 1;
    days = totalDays - totalDaysInMonths;
}

else if (totalDays < totalDaysInMonths)
{
    months = totalMonths - 1;
    int tempTotalDaysInMonths = 0;
    for (int i = months; i > 0; i--)
    {
        int month = date2.Month + i;
        int year = date1.Year;
        if (month > 12)
        {
            year++;
            int newMonth = month - 12;
            month = newMonth;
        }

        tempTotalDaysInMonths = tempTotalDaysInMonths + DateTime.DaysInMonth(year, month);
    }


    days = totalDays - tempTotalDaysInMonths;
}

else
{
    months = totalMonths;
}

return string.Format("{0} months and {1} days", months, days);

您可以使用類Month of the Time Period Library for .NET

// ----------------------------------------------------------------------
public Dictionary<DateTime,int> CountMonthDays( DateTime start, DateTime end )
{
  Dictionary<DateTime,int> monthDays = new Dictionary<DateTime, int>();

  Month startMonth = new Month( start );
  Month endMonth = new Month( end );

  if ( startMonth.Equals( endMonth ) )
  {
    monthDays.Add( startMonth.Start, end.Subtract( start ).Days );
    return monthDays;
  }

  Month month = startMonth;
  while ( month.Start < endMonth.End )
  {
    if ( month.Equals( startMonth ) )
    {
      monthDays.Add( month.Start, month.DaysInMonth - start.Day + 1 );
    }
    else if ( month.Equals( endMonth ) )
    {
      monthDays.Add( month.Start, end.Day );
    }
    else
    {
      monthDays.Add( month.Start, month.DaysInMonth );
    }
    month = month.GetNextMonth();
  }

  return monthDays;
} // CountMonthDays

用法:

// ----------------------------------------------------------------------
public void CountDaysByMonthSample()
{
  DateTime start = new DateTime( 2011, 3, 30 );
  DateTime end = new DateTime( 2011, 4, 5 );

  Dictionary<DateTime, int> monthDays = CountMonthDays( start, end );
  foreach ( KeyValuePair<DateTime, int> monthDay in monthDays )
  {
    Console.WriteLine( "month {0:d}, days {1}", monthDay.Key, monthDay.Value );
  }
  // > month 01.03.2011, days 2
  // > month 01.04.2011, days 5
} // CountDaysByMonthSample

簡單是,快速否:

    DateTime StartDate = new DateTime(2011, 3, 30);
    DateTime EndDate = new DateTime(2011, 4, 5);

    int[] DaysPerMonth = new int[12];

    while (EndDate > StartDate)
    {
        DaysPerMonth[StartDate.Month]++;
        StartDate = StartDate.AddDays(1);
    }

這是我的解決方案。 我做了一個快速檢查,它似乎工作......如果有任何問題,請告訴我:

    public Dictionary<DateTime, int> GetMontsBetween(DateTime startDate, DateTime EndDate)
    {
        Dictionary<DateTime, int> rtnValues = new Dictionary<DateTime, int>();
        DateTime startMonth = new DateTime(startDate.Year, startDate.Month, 1);
        DateTime endMonth = new DateTime(EndDate.Year, EndDate.Month, 1);
        //some checking
        if (startDate >= EndDate)
        {
            rtnValues.Add(startMonth, 0); // Or return null;
        }
        else if (startDate.Month == EndDate.Month && startDate.Year == EndDate.Year)
        {
            rtnValues.Add(startMonth, EndDate.Day - startDate.Day);
        }
        else
        {
            //Add first month remaining days
            rtnValues.Add(startMonth, DateTime.DaysInMonth(startDate.Year, startDate.Month) - startDate.Day);
            //Add All months days inbetween
            for (DateTime st = startMonth.AddMonths(1); st < endMonth; st = st.AddMonths(1))
            {
                rtnValues.Add(new DateTime(st.Year, st.Month, 1), DateTime.DaysInMonth(st.Year, st.Month) );
            }
            //Add last month days
            rtnValues.Add(new DateTime(EndDate.Year, EndDate.Month, 1), EndDate.Day);
        }
        return rtnValues;
    }

使用 linqpad 進行非常快速和骯臟的運行:

DateTime start = DateTime.Parse("03/30/2011");
DateTime end = new DateTime(2011,04,05,23,59,59);

var startNextMonthFirstDay = new DateTime(start.Year, start.Month+1, 1);

var diffForStartMonth = (startNextMonthFirstDay - start);

var totalDiff = (end-start);

var diff = Math.Round(totalDiff.TotalDays);

var diffForEndMonth = diff - diffForStartMonth.Days;


Dictionary<DateTime, int> result = new Dictionary<DateTime, int>();
result.Add(new DateTime(start.Year, start.Month, 1), diffForStartMonth.Days);
result.Add(new DateTime(end.Year, end.Month, 1), (int)diffForEndMonth);

//Dictionary<DateTime,int>{{new DateTime(2011,3,1),2},{new DateTime(2011,4,1),5}}

result.Dump();
DateTime dt1 = new DateTime(2011, 12, 12);
DateTime dt2 = new DateTime(2011, 06, 12);

TimeSpan ts = dt1.Subtract(dt2);

String s = ts.Days.ToString();

MessageBox.Show(s);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM