两个选定日期之间的天数

时间:2012-05-14 04:54:49

标签: c# datetime

  

可能重复:
  Days difference between two dates

我需要知道两个选定日期之间的天数。 通常用于比较日期我使用DateTime.CompareTo,但这里情况不同。 提前谢谢,抱歉愚蠢的问题。

3 个答案:

答案 0 :(得分:6)

使用此:

   int DaysBetween(DateTime d1, DateTime d2) {
    TimeSpan span = d2.Subtract(d1);
    return Math.Abs((int)span.TotalDays);
}

///

Console.WriteLine(DaysBetween(DateTime.Now.AddDays(10), DateTime.Now) );

将返回10

答案 1 :(得分:1)

不是原创解决方案,但是:

DateTime d1=DateTime.MinValue;
DateTime d2=DateTime.MaxValue;
TimeSpan span=d2-d1;
Console.WriteLine
         ( "There're {0} days between {1} and {2}" , span.TotalDays, d1.ToString(), d2.ToString() );

来源:http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0625cefa-461b-4a3c-b7f0-d39d06741b70/

答案 2 :(得分:1)

试试这个(你可以使用.net TimeSpan类改进它)

        public static int DateDiff(string Interval, DateTime Date1, DateTime Date2)
    {
        int difVale = 0;
        DateTime startDate, endDate;

        if (Date1 > Date2)
        {
            endDate = Date1; 
            startDate = Date2;
        }
        else
        {
            startDate = Date1; 
            endDate = Date2;
        }
        switch (Interval)
        {
            case "D":
            case "d":
                for (int nYear = startDate.Year; nYear < endDate.Year; nYear++)
                {
                    difVale += new DateTime(nYear, 12, 31).DayOfYear;
                }
                difVale += endDate.DayOfYear - startDate.DayOfYear;
                break;

            case "M":
            case "m":
                difVale = endDate.Year - startDate.Year;
                difVale = difVale * 12;
                difVale += endDate.Month - startDate.Month;
                break;
            case "Y":
            case "y":
                difVale = endDate.Year - startDate.Year;
                break;
        }
        if (Date1 > Date2)
        {
            difVale = -difVale;
        }
        return difVale;
    }