秒转年天时分秒

本文介绍了一段使用C#编写的代码,该代码能够将输入的秒数转换为包含年、天、小时、分钟和秒的时间格式字符串。通过递进判断不同时间单位的条件,实现了对秒数的精确转换。

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

public string SecToTime(int InSecond)
    {
        int years = 0;
        int Days = 0;
        int Hours = 0;
        int Minutes = 0;
        int Seconds = 0;
        if (InSecond >= 31556926)
        {
            years = Convert.ToInt32(InSecond / 31556926);
            InSecond = (InSecond % 31556926);
        }
        if (InSecond >= 86400)
        {
            Days = Convert.ToInt32(InSecond / 86400);
            InSecond = (InSecond % 86400);
        }
        if (InSecond >= 3600)
        {
            Hours = Convert.ToInt32(InSecond / 3600);
            InSecond = (InSecond % 3600);
        }
        if (InSecond >= 60)
        {
            Minutes = Convert.ToInt32(InSecond / 60);
            InSecond = (InSecond % 60);
        }
        Seconds = Convert.ToInt32(InSecond);
        
        if(years>0)
        {
            return string.Format("{0}年{1}天{2}小时{3}分{4}秒", years,Days, Hours, Minutes, Seconds);
        }else if(Days>0)
        {
            return string.Format("{0}天{1}小时{2}分{3}秒", Days, Hours, Minutes, Seconds);
        }
        else if (Hours > 0)
        {
            return string.Format("{0}小时{1}分{2}秒",  Hours, Minutes, Seconds);
        }
        else if (Minutes > 0)
        {
            return string.Format("{0}分{1}秒", Minutes, Seconds);
        }
        else
        {
            return string.Format("{0}秒", Seconds);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值