unity 获取时间

本文介绍了如何在C#中使用DateTime类获取当前本地时间和世界时间,并详细展示了获取年月日时分秒的方法。适合开发者理解日期时间处理的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:https://blog.csdn.net/qq_29533101/article/details/104551510
        Debug.Log(System.DateTime.Now);        // 当前本地时间 (年月日时分秒) -- 10/4/2018 9:38:19 PM
        Debug.Log(System.DateTime.UtcNow);     // 当前世界时间 (年月日时分秒) -- 10/4/2018 1:38:19 PM
        Debug.Log(System.DateTime.Now.Year);   // 当前时间 (年)
        Debug.Log(System.DateTime.Now.Month);  // 当前时间 (月)
        Debug.Log(System.DateTime.Now.Day);    // 当前时间 (日)
        Debug.Log(System.DateTime.Now.Hour);   // 当前时间 (时)
        Debug.Log(System.DateTime.Now.Minute); // 当前时间 (分)
        Debug.Log(System.DateTime.Now.Second); // 当前时间 (秒)

原文链接:https://blog.csdn.net/qq_29533101/article/details/104551510

### Unity获取当前时间的方法 在Unity中,可以使用C#的`System.DateTime`类来获取当前时间。以下是几种常见的方法: 1. 使用`DateTime.Now`获取本地时间: 通过`DateTime.Now`可以直接获取当前的本地时间[^1]。 ```csharp DateTime now = DateTime.Now; Debug.Log("当前北京时间:" + now); ``` 2. 使用`DateTime.UtcNow`获取国际标准时间(UTC): 如果需要获取的是协调世界时(UTC),可以使用`DateTime.UtcNow`[^1]。 ```csharp DateTime utcNow = DateTime.UtcNow; Debug.Log("当前国际时间:" + utcNow); ``` 3. 格式化时间为字符串并显示: 可以将获取时间格式化为指定的字符串形式,并将其显示在UI组件上[^2]。 ```csharp using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class ShowTime : MonoBehaviour { public TextMeshProUGUI time; private void Update() { string currentTime = System.DateTime.Now.ToString("HH:mm:ss"); // 获取当前时间并格式化为字符串 time.text = currentTime; // 将当前时间字符串赋值给 Text 组件的 text 属性 } } ``` 4. 自定义时间格式化函数: 如果需要自定义时间格式,可以编写一个函数来返回特定格式的时间字符串[^3]。 ```csharp private string GetCurrentTime() { DateTime dateTime = DateTime.Now; string strNowTime = string.Format("{0:D}{1:D}{2:D}{3:D}{4:D}{5:D}", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second); print(strNowTime); return strNowTime; } ``` 以上方法均基于`System.DateTime`类实现,能够满足大多数场景下的时间获取需求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值