.Net/C# --- 秒数转换为时分秒格式或者计算时间差

文章提供了一个C#方法,用于将秒数转换为时分秒格式(例如01:37:18),以及计算两个日期时间之间的差值。方法基于TimeSpan和DateTime类,可用于处理时间相关的计算和显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分享一个把秒转换为时分秒格式的小方法:01:37:18就是这种格式。

我们可以封装一个私密方法,也可以直接写在主方法体里面:

        /// <summary>
        /// 秒数转化为时分秒格式
        /// </summary>
        /// <param name="duration">秒数</param>
        /// <returns></returns>
        private static string sec_to_hms(long duration)
        {
            TimeSpan ts = new TimeSpan(0, 0, Convert.ToInt32(duration));
            string str = "";
            if (ts.Hours > 0)
            {
                str = String.Format("{0:00}", ts.Hours) + ":" + String.Format("{0:00}", ts.Minutes) + ":" + String.Format("{0:00}", ts.Seconds);
            }
            if (ts.Hours == 0 && ts.Minutes > 0)
            {
                str = "00:" + String.Format("{0:00}", ts.Minutes) + ":" + String.Format("{0:00}", ts.Seconds);
            }
            if (ts.Hours == 0 && ts.Minutes == 0)
            {
                str = "00:00" + String.Format("{0:00}", ts.Seconds);
            }
            return str;
        }

我们这个方法主要用的事TimeSpan。这个用处很广,可以用作时间截取之类的操作。可以用来计算时间差。

        /// <summary>
        /// 计算时间差
        /// </summary>
        /// <param name="time">时间:如:2024-01-01</param>
        /// <returns></returns>
        private static string timecha(string time)
        {
            DateTime Time2 = DateTime.Now;
            DateTime Time3 = Convert.ToDateTime(time);
            TimeSpan c = Time2 - Time3;
            int d = c.Days;//天
            int h = c.Hours;//时
            int m = c.Minutes;//分
            int s = c.Seconds;//秒
            string t = "相差" + d + "天" + h + "时" + m + "分" + s + "秒";
            return t;
        }

非常方便,在一些时间计算方便可以用得到!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值