前言:
Unity 中,游戏中常需要用到时间与时间戳之间的相互转换。这里做个备录一下。
具体实现如下:
时间戳 转换为时间:
// 时间戳 转换为时间
public DateTime StampToDateTime(string timeStamp)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long mTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(mTime);
Debug.Log("\n 当前时间为:" + startTime.Add(toNow).ToString("yyyy/MM/dd HH:mm:ss:ffff"));
return startTime.Add(toNow);
}
时间转时间戳:
// 时间转时间戳
public string DateTimeToStamp(DateTime now)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(now - startTime).TotalMilliseconds; // 相差毫秒数
Debug.Log("\n 当前 时间戳为:" + timeStamp);
return timeStamp.ToString();
}
// 调用:
DateTime nowTime = new DateTime(2018,01,24,00,00,00);
string str = DateTimeToStamp(nowTime);
StampToDateTime(str);
打印结果:
备注:
在Unity 中 制作一个时间转换工具:
这样可以在 需要时,自动转换为时间戳,就更方便啦~
完整代码(C#):
using System;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.Text;
using UnityEditor;
public class ComputeTimes : EditorWindow
{
private string inputTime = "2018,01,25,11,43,50";
// 添加 到Tool 菜单栏 : EditorWindow
[MenuItem("Tools/计算时间戳")]
static public void OpenBMFontMaker()
{
EditorWindow.GetWindow<ComputeTimes>(false, "计算时间戳", true).Show();
}
private void OnGUI()
{
GUILayout.BeginHorizontal();
GUILayout.Label("输入时间:");
inputTime = GUILayout.TextField(inputTime);
GUILayout.EndHorizontal();
GUILayout.Space(10);
if (GUILayout.Button("转换时间戳"))
{
Debug.Log("\n 当前输入字符串为:" + inputTime); //str.ToString();
DateTime nowTime = new DateTime(2018,01,24,00,00,00);
string str = DateTimeToStamp(nowTime);
StampToDateTime(str);
}
}
// 时间戳 转换为时间
public DateTime StampToDateTime(string timeStamp)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long mTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(mTime);
Debug.Log("\n 当前时间为:" + startTime.Add(toNow).ToString("yyyy/MM/dd HH:mm:ss:ffff"));
return startTime.Add(toNow);
}
// 时间转时间戳
public string DateTimeToStamp(DateTime now)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(now - startTime).TotalMilliseconds; // 相差毫秒数
Debug.Log("\n 当前 时间戳为:" + timeStamp);
return timeStamp.ToString();
}
}
// 额,最后备注一下,本来是想实现,输入时间,自动转换为时间戳的。这里没实现到,需要在代码手动添加时间。(有兴趣的,自己动手改一下吧)