C# datetime difference(year, month, day, hour, minute, and second)

Lionsure 2020-09-03 Original by the website

It is often necessary to calculate the interval between two dates in the process of website development, sometimes it needs to return a few days, sometimes it needs to return a few hours, etc. The following source code returns different values from years to microseconds to meet various needs.

The basic idea of the realization: use the Subtract method of "TimeSpan" class to calculate the time difference between the two dates, and then return the specific time difference according to the time interval "flag". If the "flag" does not match any value in the method, it returns 0

 

/// <summary>
       /// C# datetime difference in seconds, minutes, hours, days, months and years
       /// </summary>
       /// <param name="dt1">Date 1</param>
       /// <param name="dt2">Date 2</param>
       /// <param name="flag">Interval flags, such as h, m, s represent hour, minute, and second respectively</param>
       /// <returns>Difference between two dates</returns>

       private int TimeDiff(DateTime dt1, DateTime dt2, string flag)
       {
              double yearLen = 365;//Length of year, 365 days       
              double monthLen = (365 / 12);//Average number of days per month

       TimeSpan ts1 = new TimeSpan(dt1.Ticks);
              TimeSpan ts2 = new TimeSpan(dt2.Ticks);
              TimeSpan ts = ts1.Subtract(ts2).Duration();

       switch (flag)
              {
                     case "y"://Returns the year difference between two dates
                            return Convert.ToInt32(ts.Days / yearLen);
                     case "M"://Returns the month difference between two dates
                            return Convert.ToInt32(ts.Days / monthLen);
                     case "d"://Returns the difference in days between two dates
                            return ts.Days;
                     case "h"://Returns the hour difference between two dates
                            return ts.Hours;
                     case "m"://Returns the minute difference between two dates
                            return ts.Minutes;
                     case "s"://Returns the difference in seconds between two dates
                            return ts.Seconds;
                     case "ms"://Returns the difference in microseconds between the two times
                            return ts.Milliseconds;
                     default:
                            return 0;
              }
       }

Just copy this method to the public class and call it directly. It is very convenient to call. Calling method:

TimeDiff(DateTime.Now, "2020-9-3", "h")