-2

可能重复:
两个日期之间的天数差异

我需要知道两个选定日期之间的天数。通常用于比较我使用 DateTime.CompareTo 的日期,但这里的情况有所不同。在此先感谢,并对愚蠢的问题感到抱歉。

4

3 回答 3

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

于 2012-05-14T04:56:59.377 回答
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/

于 2012-05-14T04:57:30.487 回答
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;
    }
于 2012-05-14T05:37:35.413 回答