计算两时间之前的差值时长,并转换成时分秒的字符串格式

        /// <summary>
        /// 返回时间差的总时长,以*天*时*分*秒的格式
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="overTime"></param>
        /// <returns></returns>
        public static string ConvertDurationToStr(DateTime startTime, DateTime overTime)
        {
            var val = (long)(overTime - startTime).TotalMilliseconds;
            return DurationToStr(val);
        }

        /// <summary>
        /// 返回时间差的总时长,以*天*时*分*秒的格式
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="overTime"></param>
        /// <returns></returns>
        public static string ConvertDurationToStr(TimeSpan startTime, TimeSpan overTime)
        {
            var val = (long)(overTime - startTime).TotalMilliseconds;
            return DurationToStr(val);
        }

        /// <summary>
        /// 时长转化成字符串
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        static string DurationToStr(long val)
        {
            var dt = new TimeSpan(val * 10000);
            StringBuilder sb = new StringBuilder();
            if (dt.Days > 0)
            {
                sb.Append($"{dt.Days}天");
            }
            if (dt.Hours > 0)
            {
                sb.Append($"{dt.Hours}时");
            }
            if (dt.Minutes > 0)
            {
                sb.Append($"{dt.Minutes}分");
            }
            if (dt.Seconds > 0)
            {
                sb.Append($"{dt.Seconds}秒");
            }
            if (dt.Milliseconds > 0)
            {
                sb.Append($"{dt.Milliseconds}毫秒");
            }
            return sb.ToString();
        }

 

posted @ 2024-01-18 10:44  吃奶嘴的路飞  阅读(2)  评论(0编辑  收藏  举报