时间戳与 DateTime 的转换
时间戳转 DateTime
原理:时间戳是指格林威治时间 1970 年 01 月 01 日 00 时 00 分 00 秒 (北京时间 1970 年 01 月 01 日 08 时 00 分 00 秒) 起至现在的总秒数。在 Unity 中,可以通过将时间戳的值作为参数,创建一个 DateTime 对象。在底层,.NET 框架会根据时间戳的值计算出对应的年、月、日、时、分、秒等时间分量,从而构建出一个具体的日期时间对象。
DateTime 转时间戳
原理:获取 DateTime 对象所表示的时间与 1970 年 1 月 1 日 00:00:00 之间的时间间隔,然后将这个时间间隔转换为秒数或毫秒数,这个数值就是对应的时间戳。计算过程中,会考虑到闰年、每月的天数不同等历法规则,精确计算出两个时间点之间的时间差。
秒数与时分秒格式的转换
秒数转时分秒
原理:基于 60 进制的时间换算规则。首先将总秒数除以 3600,得到的商就是小时数;然后将总秒数对 3600 取余,得到剩余的秒数,再将这个余数除以 60,得到的商就是分钟数;最后将上一步的余数作为秒数。
时分秒转秒数
原理:将小时数乘以 3600,分钟数乘以 60,然后将这两个结果与秒数相加,就得到了对应的总秒数。
Unity 时间格式与其他时间格式的转换
原理:Unity 中有自己的时间表示和管理方式,如 Time 类用于处理游戏中的时间相关操作。要将 Unity 的时间格式与其他时间格式进行转换,通常需要根据各自的时间基准和单位进行换算。例如,将 Unity 的游戏时间(以秒为单位)转换为 DateTime 格式时,需要确定一个起始时间点,然后根据游戏时间的流逝计算出对应的 DateTime。在转换过程中,需要考虑到不同系统或平台的时间差异、时区设置等因素,以确保时间转换的准确性。
一、计时器的写法
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShiJian : MonoBehaviour {
public Text text;
public Text text1;
float SpendTime;
int hour;int minute;int second;int milliScecond;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
DateTime Time1 = DateTime.Now.ToLocalTime();
text.text = Time1.ToString("yyyy-MM-dd HH:mm:ss");
SpendTime += Time.deltaTime;
hour = (int)SpendTime / 3600;
minute = (int)(SpendTime - hour * 3600 )/60;
second = (int)(SpendTime - hour * 3600 - minute * 60);
milliScecond = (int)((SpendTime - (int)SpendTime) * 1000);
text1.text = string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D3}",
hour, minute, second,milliScecond);
}
}
AI 代码解读
二、第二种转换方式-总用时转换成时分秒(两种方式)
if (aa)
{
Shi = Convert.ToInt32(field.text) / 3600;
Fen = Convert.ToInt32(field.text) % 3600 / 60;
miao = Convert.ToInt32(field.text) % 60;
text.text = Shi + ":" + (int)Fen + ":" + miao;
}
if (aa )
{
Shi = (int)Convert.ToInt32(field.text) / 3600;
Fen = (int)(Convert.ToInt32(field.text) - Shi * 3600) / 60;
miao = (int)(Convert.ToInt32(field.text) - Shi * 3600 - Fen * 60);
text.text = Shi + ":" + (int)Fen + ":" + miao;
}
AI 代码解读