C# 计算时间间隔,两个时间差(年月日时分秒)

 参考:https://www.cnblogs.com/hllive/articles/10592812.html

    public class Program
    {
        /// <summary>
        /// 计算两个时间差(年月日时分秒)
        /// </summary>
        /// <param name="b">开始时间</param>
        /// <param name="e">结束时间</param>
        /// <returns></returns>
        private static string term(DateTime b, DateTime e)
        {
            if (b < e)
            {
                var t = new
                {
                    bm = b.Month,
                    em = e.Month,
                    bd = b.Day,
                    ed = e.Day
                };
                int diffMonth = (e.Year - b.Year) * 12 + (t.em - t.bm),//相差月
                    diffYear = diffMonth / 12;//相差年

                int[] d = new int[3] { 0, 0, 0 };
                if (diffYear > 0)
                {
                    if (t.em == t.bm && t.ed < t.bd)
                    {
                        d[0] = diffYear - 1;
                    }
                    else d[0] = diffYear;
                }

                if (t.ed >= t.bd)
                {
                    d[1] = diffMonth % 12;
                    d[2] = t.ed - t.bd;
                }
                else//结束日 小于 开始日
                {
                    int dm = diffMonth - 1;
                    d[1] = dm % 12;
                    TimeSpan ts = e - b.AddMonths(dm);
                    d[2] = ts.Days;
                }
                StringBuilder sb = new StringBuilder();

                if (d.Sum() > 0)
                {
                    if (d[0] > 0) sb.Append(string.Format("{0}年", d[0]));
                    if (d[1] > 0) sb.Append(string.Format("{0}个月", d[1]));
                    if (d[2] > 0) sb.Append(string.Format("{0}天", d[2]));
                }
                else
                {
                    int[] time = new int[2] { 0, 0 };
                    TimeSpan sj = e - b;
                    time[0] = sj.Hours;
                    time[1] = sj.Minutes % 60;
                    if (time[0] > 0) sb.Append(string.Format("{0}小时", time[0]));
                    if (time[1] > 0) sb.Append(string.Format("{0}分钟", time[1]));
                    if (time.Sum() <= 0) sb.Append(string.Format("{0}秒", sj.Seconds));
                }
                return sb.ToString();
            }
            else throw new Exception("开始日期必须小于结束日期");
        }
        static void Main(string[] args)
        {
            DateTime begin = new DateTime(2021, 9, 23,16,47,9);
            DateTime end = DateTime.Now;
            string s = term(begin, end);
            Console.WriteLine(s);
            
        }

    }

 

上一篇:91821-ReplaceSpace


下一篇:九月二十三