GetHttpTimer.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. public class GetHttpTimer : MonoSingleton<GetHttpTimer>
  7. {
  8. public long timestamp = -1;
  9. private float nowTimes = 0;
  10. private void Start()
  11. {
  12. StartCoroutine(HttpTool.Instance.SendHttp(HttpEdustryAction.timestamp, "", (string msg) =>
  13. {
  14. Debug.Log(msg);
  15. JObject data = JObject.Parse(msg);
  16. if (data["code"].ToString() == "200")
  17. {
  18. timestamp = long.Parse(data["data"]["timestamp"].ToString());
  19. nowTimes = 0;
  20. Debug.Log(timestamp);
  21. }
  22. else
  23. {
  24. Debug.LogError(HttpEdustryAction.timestamp + " Error " + data["code"].ToString());
  25. }
  26. }));
  27. }
  28. void Update()
  29. {
  30. if (timestamp !=-1)
  31. {
  32. nowTimes += Time.deltaTime;
  33. // timestamp += Convert.ToInt64(Time.deltaTime);
  34. }
  35. }
  36. public DateTime GetTimer()
  37. {
  38. if (timestamp == -1)
  39. return System.DateTime.Now;
  40. return UnixTimeStampToDateTime((timestamp+(long)nowTimes));
  41. }
  42. // 将Unix时间戳转换为DateTime
  43. DateTime UnixTimeStampToDateTime(long unixTimeStamp)
  44. {
  45. // string times = unixTimeStamp.ToString() + "000";
  46. // long timestamp = long.Parse(times);
  47. // Unix起始时间
  48. // DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.);
  49. DateTime startTime = System.TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//获取时间戳
  50. DateTime dt = startTime.AddSeconds(unixTimeStamp);
  51. // 将时间戳转换为DateTime
  52. return dt;
  53. }
  54. /// <summary>
  55. /// 时间戳转为C#格式时间
  56. /// </summary>
  57. /// <param name=”timeStamp”></param>
  58. /// <returns></returns>
  59. public static DateTime ConvertStringToDateTime(string timeStamp)
  60. {
  61. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  62. long lTime = long.Parse(timeStamp + "0000");
  63. TimeSpan toNow = new TimeSpan(lTime);
  64. return dtStart.Add(toNow);
  65. }
  66. }