【Unity】【C#】DateTime時間字串,月份用英文顯示
阿新 • • 發佈:2019-01-10
製作一個鐘錶,要求效果如下圖:
由於每一部分的字型大小不同,我分別使用了不同的Text控制元件。(不懂dalao們有沒有更科學的辦法)
把這些Text控制元件包含在一個Object下,給該Object定義一個指令碼,分別引用這些控制元件。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 顯示當前的系統時間
/// </summary>
public class TimeScript : MonoBehaviour {
public Text HourText; // 時
public Text MinuteText; // 分
public Text DateText; // 23
public Text MonthText; // MAR
public Text WeekText; // THU
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//取得現在的時間
DateTime now = DateTime.Now;
HourText.text = now.ToString("HH"); // HH是24時制,hh是12時制
MinuteText.text = now.ToString("mm");
DateText.text = now.ToString("dd");
MonthText.text = now.ToString("MMMM", new System.Globalization.CultureInfo("en-us")).Substring(0, 3); // 月份只要洋文的前三個字母
WeekText.text = now.ToString("dddd").Substring(0, 3); // 星期只要洋文的前三個字母
}
}
小結:
- 時間字串使用DateTime類。
- 月份獲取到的是數字(如12月是返回12),想要改成英文,國際化的方法參見上面程式碼(省去自己寫12個列舉)。
其他字串操作的相關參考: