#时间格式转换为时间戳(互转)
时间戳定义为从格林威治时间 1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
using UnityEngine;
using System.Collections;
using System;
public class DateTime_TimeStamp : MonoBehaviour
{
protected int m_timestamp;
private int GetTimeStamp(DateTime dt)// 获取时间戳Timestamp
{
DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
int timeStamp = Convert.ToInt32((dt - dateStart).TotalSeconds);
return timeStamp;
}
private DateTime GetDateTime(int timeStamp)//时间戳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;
}
private DateTime GetDateTime(string timeStamp)// 时间戳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")));
}
}