当前位置: 首页 > 工具软件 > timespans > 使用案例 >

C# 获取时间差(DateTime,TimeSpan)

裴昕
2023-12-01

计算时间差值

/// <summary>
        /// 获取时间差的Ticks数
        /// </summary>
        /// <param name="timeStart">起始时间</param>
        /// <param name="timeEnd">截止时间</param>
        /// <returns></returns>
        public static long GetDateDiffSeconds(DateTime timeStart,DateTime timeEnd)
        {
            long l = (timeEnd.Ticks - timeStart.Ticks) / 10000000;
            return l;
        }

        /// <summary>
        /// 获取时间差字符串
        /// </summary>
        /// <param name="timeStart">起始时间</param>
        /// <param name="timeEnd">截止时间</param>
        /// <returns></returns>
        public static string GetDateDiff(DateTime timeStart, DateTime timeEnd)
        {
            TimeSpan timeSpanS = new TimeSpan(timeStart.Ticks);
            TimeSpan timeSpanE = new TimeSpan(timeEnd.Ticks);
            TimeSpan timeDiff = timeSpanE.Subtract(timeSpanS);

            string days = timeDiff.Days.ToString();                 //获取时间差值的天数
            string hours = timeDiff.Hours.ToString();               //获取时间差值的小时数
            string minutes = timeDiff.Minutes.ToString();           //获取时间差值的分钟数
            string seconds = timeDiff.Seconds.ToString();           //获取时间差值的秒钟数
            string result=string.Format("From {0} to {1},it crossed  {2} Days ,{3} Hours , {4} Minutes ,{5} Seconds. ",timeStart,timeEnd,days,hours,minutes,seconds);
            return result;
        }

用法:
1.对时间间隔上有较明确要求的程序。

 类似资料: