</pre><pre name="code" class="csharp">using UnityEngine;
using System.Collections;
using System;
/// <summary>
/// C#时间格式转换为时间戳(互转)
/// 时间戳定义为从格林威治时间 1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
/// </summary>
public class DateTime_TimeStamp : MonoBehaviour
{
protected int m_timestamp;
/// <summary>
/// 获取时间戳Timestamp
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private int GetTimeStamp(DateTime dt)
{
DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
int timeStamp = Convert.ToInt32((dt - dateStart).TotalSeconds);
return timeStamp;
}
/// <summary>
/// 时间戳Timestamp转换成日期
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
private DateTime GetDateTime(int timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = ((long)timeStamp * 10000000);
TimeSpan toNow = new TimeSpan(lTime);
DateTime targetDt = dtStart.Add(toNow);
return targetDt;
}
/// <summary>
/// 时间戳Timestamp转换成日期
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
private DateTime GetDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
DateTime targetDt = dtStart.Add(toNow);
return dtStart.Add(toNow);
}
void OnGUI()
{
if (GUILayout.Button("获取当前时间的时间戳"))
{
DateTime dtNow = DateTime.Now;
m_timestamp = GetTimeStamp(dtNow);
Debug.Log(string.Format("获取当前时间的时间戳 = {0} -> {1}", dtNow.ToString("yyyy-MM-dd hh:mm:ss"), m_timestamp));
}
if (GUILayout.Button("将时间戳转换成日期_1"))
{
DateTime dt = GetDateTime(m_timestamp);
Debug.Log(string.Format("将时间戳转换成日期_1 = {0} -> {1}", m_timestamp, dt.ToString("yyyy-MM-dd hh:mm:ss")));
}
if (GUILayout.Button("将时间戳转换成日期_2"))
{
DateTime dt = GetDateTime(m_timestamp.ToString());
Debug.Log(string.Format("将时间戳转换成日期_2 = {0} -> {1}", m_timestamp, dt.ToString("yyyy-MM-dd hh:mm:ss")));
}
}
}