【问题标题】:how many days between two selected dates [duplicate]两个选定日期之间的天数[重复]
【发布时间】:2012-05-21 14:29:26
【问题描述】:

可能重复:
Days difference between two dates

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

【问题讨论】:

标签: c# datetime


【解决方案1】:

使用这个:

   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

【讨论】:

  • (int)span.TotalDays = span.Days 对吗?你为什么不直接退货?
【解决方案2】:

不是原始解决方案,而是:

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/

【讨论】:

    【解决方案3】:

    试试这个(你可以使用 .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-07-31
      • 1970-01-01
      • 2017-07-05
      • 2012-06-07
      • 2012-12-07
      • 2013-07-24
      • 1970-01-01
      • 2014-07-08
      相关资源
      最近更新 更多