【Unity】Unity中获取网络时间进行每日和每月刷新

直接上代码

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DateChecker : MonoBehaviour
{
    private DateTime lastCheckedDate; //上次刷新日数据的日期
    
    private DateTime lastMonthUtc; //上次刷新月数据的日期

    TimeSpan NowOffestTime = TimeSpan.Zero;

    private void Start()
    {
        getServerTime();
        lastCheckedDate = DateTime.Parse(PlayerPrefs.GetString("LASTCHECKDATE", DateTime.MinValue.Date.ToString())); //DateTime.UtcNow.Date;
        lastMonthUtc = DateTime.Parse(PlayerPrefs.GetString("LASTMONTHDATE", DateTime.MinValue.Date.ToString()));

        //CheckAndUpdateData();
    }

    private void CheckAndUpdateData()
    {
        DateTime currentDate = GetNowTime();//DateTime.UtcNow.Date;

        if (currentDate > lastCheckedDate)
        {
            PlayerPrefs.SetString("LASTCHECKDATE", currentDate.ToString());
            UpdateDailyData();
            lastCheckedDate = currentDate;
        }

        if (currentDate.Month > lastMonthUtc.Month || currentDate.Year > lastMonthUtc.Year) //每月刷新
        {
            PlayerPrefs.SetString("LASTMONTHDATE", currentDate.ToString());
            UpdateMonthData();
            lastMonthUtc = currentDate;
        }
    }

    private void UpdateDailyData()
    {
		//在这里写需要每日刷新的数据
    }

    private void UpdateMonthData()
    {
		//在这里写需要每月刷新的数据

    }

    /// <summary>
    /// 获取实际的网络时间 切系统时间也没用
    /// </summary>
    /// <returns></returns>
    public DateTime GetNowTime()
    {
        return DateTime.Now - NowOffestTime;
    }
    //获得服务器时间
    public void getServerTime()
    {
        string url = "https://github.com";
        StartCoroutine(IServerTime(url));
    }

    IEnumerator IServerTime(string url)
    {
        Debug.Log("开始获取“+url+”的服务器时间(GMT DATE)");
        WWW www = new WWW(url);
        yield return www;
        if (www.isDone && string.IsNullOrEmpty(www.error))
        {
            Dictionary<string, string> resHeaders = www.responseHeaders;
            string key = "DATE";
            string value = null;
            if (resHeaders != null && resHeaders.ContainsKey(key))
            {
                resHeaders.TryGetValue(key, out value);
            }

            if (value == null)
            {
                Debug.Log("DATE is null");
                yield break;
            }

            DateTime Gmt = GMT2Local(value);
            DateTime now = DateTime.Now;

            //if (IsNewerHour(now, Gmt))
            {
                //记录一下时间差 这就是用户手动改的时间与世界时间的间隔
                //之后调用GetNowTime()就是准确时间
                NowOffestTime = now - Gmt;
                CheckAndUpdateData();
            }
        }
    }

    /// <summary>
    /// GMT时间转成本地时间全世界各个时区都会自动转换
    /// </summary>
    /// <param name="gmt">字符串形式的GMT时间</param>
    /// <returns></returns>
    public DateTime GMT2Local(string gmt)
    {
        DateTime dt = DateTime.MinValue;
        try
        {
            string pattern = "";
            if (gmt.IndexOf("+0") != -1)
            {
                gmt = gmt.Replace("GMT", "");
                pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
            }
            if (gmt.ToUpper().IndexOf("GMT") != -1)
            {
                pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
            }
            if (pattern != "")
            {
                dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
                dt = dt.ToLocalTime();
            }
            else
            {
                dt = Convert.ToDateTime(gmt);
            }
        }
        catch
        {
        }
        return dt;
    }
    /// <summary>
    /// time0:当下的日子
    /// time1:被比较的日子
    /// </summary>
    /// <param name="time0"></param>
    /// <param name="time1"></param>
    /// <returns></returns>
    public static bool IsNewerHour(DateTime time0, DateTime time1)
    {
        bool isNewer = false;
        if (time0 > time1)
        {
            if (time0.Year > time1.Year)
                isNewer = true;
            if (time0.Month > time1.Month)
                isNewer = true;
            if (time0.Day > time1.Day)
                isNewer = true;
            if (time0.Hour > time1.Hour)
                isNewer = true;
        }
        return isNewer;
    }
}

这个代码是抓取热门网站"https://github.com"的时间,然后解析出来,获取实时的网络时间,可根据自身情况选取其他热门网站(百度、阿里等等)。

根据实时的网络时间,每次登录时,根据时间来刷新游戏中每日和每月需要刷新的数据,直接将代码挂到预制体上就能使用,可根据自身需求进行功能调整~

### Unity 中实现年月日时分秒功能 在 Unity 中可以利用 C# 提供的 `DateTime` 类来轻松获取并显示当前的时间,包括年、月、日、小时、分钟秒。以下是具体方法: #### 获取当前时间 通过调用 `DateTime.Now` 可以获得当前系统的日期时间对象[^1]。 ```csharp using System; public class TimeExample : MonoBehaviour { void Start() { DateTime currentTime = DateTime.Now; int year = currentTime.Year; // 当前年份 int month = currentTime.Month; // 当前月份 int day = currentTime.Day; // 当前天数 int hour = currentTime.Hour; // 当前小时 int minute = currentTime.Minute; // 当前分钟 int second = currentTime.Second; // 当前秒钟 string formattedTime = $"{year}年{month}月{day}日 {hour}:{minute}:{second}"; Debug.Log(formattedTime); } } ``` 上述代码展示了如何提取当前时间的具体组成部分,并将其格式化为类似于“2023年09月15日 14:30:45”的字符串形式。 #### 自定义时间格式 如果需要更灵活地控制输出格式,可以使用 `ToString()` 方法指定自定义格式串[^2]。例如: ```csharp string customFormattedTime = currentTime.ToString("yyyy年MM月dd日 HH:mm:ss"); Debug.Log(customFormattedTime); // 输出类似:2023年09月15日 14:30:45 ``` 这里使用的 `"yyyy年MM月dd日 HH:mm:ss"` 是一种常见的日期时间格式模板,其中大写的 `HH` 表示24小时制下的小时数。 #### 定期更新时间 为了在游戏中动态展示实时变化的时间,可以通过每帧刷新或者定时器的方式不断重新读取最新的 `DateTime.Now` 值。 ```csharp void Update() { DateTime now = DateTime.Now; string timeString = now.ToString("yyyy年MM月dd日 HH:mm:ss"); Debug.Log(timeString); } ``` 此段脚本会在每一帧都打印一次新的时间戳至控制台中。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七月.末

你的鼓励就是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值