Calculate Years, Months, weeks and Days

后端 未结 7 1088
南笙
南笙 2020-12-10 07:19

In my application, a user enters two dates. A scheduled start date, and a scheduled end date. We have to take those dates, and populate 4 fields, based on the difference.

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 08:09

    I had created this one for returning difference in years,month and days between 2 dates.

    public static Dictionary TimeSpanToDateParts(DateTime fromDate,DateTime toDate)
            {
                int years;
                int months;
                int days;
                Dictionary dateParts = new Dictionary();
                if (toDate < fromDate)
                {
                   return TimeSpanToDateParts(toDate,fromDate);
                }
    
                var span = toDate - fromDate;
    
                months = 12 * (toDate.Year - fromDate.Year) + (toDate.Month - fromDate.Month);
    
                if (toDate.CompareTo(fromDate.AddMonths(months).AddMilliseconds(-500)) <= 0)
                {
                    --months;
                }
    
                years = months / 12;
                months -= years * 12;
    
                if (months == 0 && years == 0)
                {
                    days = span.Days;
                }
                else
                {
                    days = toDate.Day;
                    if (fromDate.Day > toDate.Day)
                        days = days + (DateTime.DaysInMonth(toDate.Year, toDate.Month - 1) - fromDate.Day);
                    else
                        days = days - fromDate.Day;
                }
                dateParts.Add("Years", years);
                dateParts.Add("Months", months);
                dateParts.Add("Days", days);
    
                return dateParts;
            }
    

提交回复
热议问题