`

计算日期之间的(年月日)数

    博客分类:
  • C#
 
阅读更多
        /// <summary>
        /// 获取两日期之间的年,月,日数
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public static IDictionary<string, int> dateCount(DateTime startDate, DateTime endDate)
        {
            IDictionary<string, int> map = new Dictionary<string, int>();
            int yearCount = 0;
            int monthCount = 0;
            int dayCount = 0;
            bool canGo = (startDate - endDate).TotalDays > 0;
            while (canGo)
            {
                double dc = (startDate - endDate).TotalDays;
                if (dc >= 0)
                {
                    monthCount++;
                }
                else
                {
                    double temp = (startDate - endDate).TotalDays;
                    if (temp < 0)
                        monthCount--;
                    startDate = startDate.AddMonths(-1);
                    string str = (endDate - startDate).TotalDays.ToString();
                    dayCount = System.Math.Abs(int.Parse(str.Substring(0, str.IndexOf('.'))));
                    canGo = false;
                }
                startDate = endDate.AddMonths(1);
            }
            if (monthCount >= 12)
            {
                yearCount = monthCount / 12;
                monthCount = monthCount % 12;
            }
            map.Add("year", yearCount);
            map.Add("month", monthCount);
            map.Add("day", dayCount);
            return map;          
        }
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics