unity 获取网络时间

56 篇文章 7 订阅

网络时间

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

public class NetworkTime : MonoBehaviour
{    
    void Start()
    {
    	// 自动获取网络时间
        StartCoroutine(GetWebTime());
    }

    #region 获取网络时间

    /// <summary>
    /// 获取当前网络时间
    /// </summary>
    /// <returns></returns>
    IEnumerator GetWebTime()
    {
        // 获取时间地址
        string url = "https://www.baidu.com"; // 百度 //http://www.beijing-time.org/"; // 北京时间
        Debug.Log("开始获取服务器时间... 获取地址是: " + url);

        DateTime _webNowTime = DateTime.Now;
        // 获取时间
        UnityWebRequest WebRequest = new UnityWebRequest(url);

        // 等待请求完成
        yield return WebRequest.SendWebRequest();
        
        //网页加载完成  并且下载过程中没有错误   string.IsNullOrEmpty 判断字符串是否是null 或者是" ",如果是返回true
        //WebRequest.error  下载过程中如果出现下载错误  会返回错误信息 如果下载没有完成那么将会阻塞到下载完成
        if (WebRequest.isDone && string.IsNullOrEmpty(WebRequest.error))
        {
        	// 将返回值存为字典
            Dictionary<string, string> resHeaders = WebRequest.GetResponseHeaders();
            string key = "DATE";
            string value = null;
            // 获取key为"DATE" 的 Value值
            if (resHeaders != null && resHeaders.ContainsKey(key))
            {
                resHeaders.TryGetValue(key, out value);
            }

            if (value == null)
            {
                Debug.LogError("没有获取到key为DATE对应的Value值...");
                yield break;
            }

            // 取到了value,则进行转换为本地时间
            _webNowTime = FormattingGMT(value);
            Debug.Log(value + " ,转换后的网络时间:" + _webNowTime);

            // 转换成时间戳
            TimeSpan cha = (_webNowTime - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)));
            long t = (long) cha.TotalSeconds;
            Debug.Log("网络时间转时间戳:" + t);
        }
    }

    /// <summary>
    /// GMT(格林威治时间)时间转成本地时间
    /// </summary>
    /// <param name="gmt">字符串形式的GMT时间</param>
    /// <returns></returns>
    private DateTime FormattingGMT(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 (Exception e)
        {
            Debug.Log(e);
            Debug.LogError("时间转换错误...");
        }
        return dt;
    }
    #endregion
}


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值