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

2021/9/23 17:10:49

本文主要是介绍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);
            
        }

    }

 



这篇关于C# 计算时间间隔,两个时间差(年月日时分秒)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程