Unity3D获取系统当前时间,并格式化显示

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、运行场景,即可以看到当前时间的显示,具体如下图

 

posted @ 2019-03-26 21:32  vuciao  阅读(31121)  评论(1编辑  收藏  举报