1 顯示當(dāng)前時(shí)間,顯示的格式為20220506-11:19:30
2 輸出單位為秒的時(shí)間戳
3 輸出單位為毫秒的時(shí)間戳文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-501711.html
//Unity-DateTime顯示當(dāng)前時(shí)間和獲取時(shí)間戳
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
//1 顯示當(dāng)前時(shí)間,顯示的格式為20220506-11:19:30
//2 輸出單位為秒的時(shí)間戳
//3 輸出單位為毫秒的時(shí)間戳
public class Demo : MonoBehaviour
{
void Start()
{
GetTime();
Debug.Log($"輸出單位為秒的時(shí)間戳 = {GetTimeStampSecond()}");
Debug.Log($"輸出單位為毫秒的時(shí)間戳= {GetTimeStampMilliSecond()}");
}
/// <summary>
/// 顯示當(dāng)前時(shí)間,顯示的格式為20220506-11:09:30
/// </summary>
public void GetTime()
{
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month < 10 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString();
string day = DateTime.Now.Day < 10 ? "0" + DateTime.Now.Day.ToString() : DateTime.Now.Day.ToString();
string hour = DateTime.Now.Hour < 10 ? "0" + DateTime.Now.Hour.ToString() : DateTime.Now.Hour.ToString();
string minute = DateTime.Now.Minute < 10 ? "0" + DateTime.Now.Minute.ToString() : DateTime.Now.Minute.ToString();
string second = DateTime.Now.Second < 10 ? "0" + DateTime.Now.Second.ToString() : DateTime.Now.Second.ToString();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(year);
stringBuilder.Append(month);
stringBuilder.Append(day);
stringBuilder.Append("-");
stringBuilder.Append(hour);
stringBuilder.Append(":");
stringBuilder.Append(minute);
stringBuilder.Append(":");
stringBuilder.Append(second);
Debug.Log($"當(dāng)前時(shí)間 = {stringBuilder.ToString()}");
}
/// <summary>
/// 獲取時(shí)間戳-單位秒
/// </summary>
/// <returns></returns>
public long GetTimeStampSecond()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
try
{
return Convert.ToInt64(ts.TotalSeconds);
}
catch (Exception ex)
{
Debug.Log($"GetTimeStampSecond Error = {ex}");
return 0;
}
}
/// <summary>
/// 獲取時(shí)間戳-單位毫秒
/// </summary>
/// <returns></returns>
public long GetTimeStampMilliSecond()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
try
{
return Convert.ToInt64(ts.TotalMilliseconds);
}
catch (Exception ex)
{
Debug.Log($"GetTimeStampMilliSecond Error = {ex}");
return 0;
}
}
}
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-501711.html
到了這里,關(guān)于Unity-DateTime顯示當(dāng)前時(shí)間和獲取時(shí)間戳的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!