Unity 獲取系統當前時間,並格式化顯示。通過“System.DateTime”獲取系統當前的時間,然后通過格式化把獲得的時間格式化顯示出來,具體如下:
1、打開Unity,新建一個空工程,Unity界面如下圖
2、在工程中新建一個腳本,可以命名為“CurrrentTimeTest”,選中“CurrrentTimeTest”,雙擊打開腳本。
3、在打開 的腳本上進行編輯,首先設置幾個變量存取當前時間的時分秒,年月日,然后把取得到的時間進行格式化輸出,具體如下圖
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CurrrentTimeTest : MonoBehaviour { private Text CurrrentTimeText; private int hour; private int minute; private int second; private int year; private int month; private int day; // Use this for initialization void Start () { CurrrentTimeText = GetComponent<Text>(); } // Update is called once per frame void Update () { //獲取當前時間 hour = DateTime.Now.Hour; minute = DateTime.Now.Minute; second = DateTime.Now.Second; year = DateTime.Now.Year; month = DateTime.Now.Month; day = DateTime.Now.Day; //格式化顯示當前時間 CurrrentTimeText.text = string.Format("{0:D2}:{1:D2}:{2:D2} " + "{3:D4}/{4:D2}/{5:D2}", hour, minute, second, year, month, day); #if UNITY_EDITOR Debug.Log("W now " + System.DateTime.Now); //當前時間(年月日時分秒) Debug.Log("W utc " + System.DateTime.UtcNow); //當前時間(年月日時分秒) #endif } }
4、腳本編譯正確后,回到Unity界面,在場景中新建一個“Text”,適當調整好位置與大小,然后把“CurrentTimeTest”賦給“Text”,具體如下圖
5、運行場景,即可以看到當前時間的顯示,具體如下圖