前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【100个 Unity实用技能】☀️ | Unity 将秒数转化为00:00:00时间格式

【100个 Unity实用技能】☀️ | Unity 将秒数转化为00:00:00时间格式

作者头像
呆呆敲代码的小Y
发布2022-11-18 16:20:46
1.6K0
发布2022-11-18 16:20:46
举报

Unity 实用小技能学习

Unity 将秒数转化为00:00:00时间格式

在游戏中我们有时候会拿到玩家本次游玩某个关卡的游戏时间,拿到的时间一般是float\int。

此时需要将float\int值转换为一个时间格式,如00:00:00这种,一起看下解决方案吧。

代码语言:javascript
复制
    private void FloatForTime(float time)
    {
        //秒数取整
        int seconds = (int)time;
        //一小时为3600秒 秒数对3600取整即为小时
        int hour = seconds / 3600;
        //一分钟为60秒 秒数对3600取余再对60取整即为分钟
        int minute = seconds % 3600 / 60;
        //对3600取余再对60取余即为秒数
        seconds = seconds % 3600 % 60;
        
        //打印00:00:00时间格式
       Debug.Log($"时间:{hour:D2}:{minute:D2}:{seconds:D2}");
    }

time为传入的float值,比如传入255,则打印结果如下:

在这里插入图片描述
在这里插入图片描述

也可以简单封装一个方法专门用来将float值转换为时间格式,代码如下所示:

代码语言:javascript
复制
public class TimeDemo : MonoBehaviour
{
    private void Start()
    {
    	//打印255.55转换为时间格式
        Debug.Log(255.55f.ToTimeFormat());
    }
}

public static class FloatExtension
{
    /// 
    /// 将秒数转化为00:00:00格式
    /// 
    /// 秒数
    /// 00:00:00
    public static string ToTimeFormat(this float time)
    {
        //秒数取整
        int seconds = (int)time;
        //一小时为3600秒 秒数对3600取整即为小时
        int hour = seconds / 3600;
        //一分钟为60秒 秒数对3600取余再对60取整即为分钟
        int minute = seconds % 3600 / 60;
        //对3600取余再对60取余即为秒数
        seconds = seconds % 3600 % 60;
        //返回00:00:00时间格式
        return string.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, seconds);
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-11-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Unity 实用小技能学习
    • Unity 将秒数转化为00:00:00时间格式
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档