UtilTools.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Net;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. #if !COMBAT_SERVER
  8. using UnityEngine;
  9. #endif
  10. using System.IO;
  11. using System.Linq;
  12. using System.Runtime.Serialization.Formatters.Binary;
  13. #if !COMBAT_SERVER
  14. using UnityEngine.Profiling;
  15. #endif
  16. using System.Security.Cryptography;
  17. using Fort23.UTool;
  18. using Random = System.Random;
  19. namespace Utility
  20. {
  21. public static class UtilTools
  22. {
  23. #if !COMBAT_SERVER
  24. public static List<GameObject> allDontDestroyOnLoad = new List<GameObject>();
  25. #endif
  26. private static int m_seed = 0;
  27. private static StringBuilder sb;
  28. public static long oneDay = 86400000;
  29. public static int GenerateSeed()
  30. {
  31. m_seed++;
  32. return m_seed;
  33. }
  34. public static float FrameToDuration(int frame)
  35. {
  36. return frame * 0.02f;
  37. }
  38. public static string GetGUID()
  39. {
  40. System.Guid guid = new Guid();
  41. guid = Guid.NewGuid();
  42. string str = guid.ToString();
  43. return str;
  44. }
  45. #if !COMBAT_SERVER
  46. public static void SetDontDestroyOnLoad(GameObject go)
  47. {
  48. if (allDontDestroyOnLoad.Contains(go))
  49. {
  50. return;
  51. }
  52. GameObject.DontDestroyOnLoad(go);
  53. allDontDestroyOnLoad.Add(go);
  54. }
  55. public static int DurationToFrame(float duration)
  56. {
  57. return (int)(duration / Time.fixedDeltaTime);
  58. }
  59. #endif
  60. // public static int RoundToInt(float value)
  61. // {
  62. // return (int)System.Math.Round(value);
  63. // }
  64. #if !COMBAT_SERVER
  65. public static string CombineString(params string[] strs)
  66. {
  67. StringBuilder sb = new StringBuilder();
  68. for (int i = 0; i < strs.Length; i++)
  69. {
  70. sb.Append(strs[i]);
  71. }
  72. return sb.ToString();
  73. }
  74. public static string CombineString(params object[] strs)
  75. {
  76. if (sb == null)
  77. {
  78. sb = new StringBuilder();
  79. }
  80. sb.Clear();
  81. //StringBuilder sb = new StringBuilder();
  82. for (int i = 0; i < strs.Length; i++)
  83. {
  84. sb.Append(strs[i]);
  85. }
  86. return sb.ToString();
  87. }
  88. // /// <summary>
  89. // /// 获取描述文本
  90. // /// </summary>
  91. // /// <param name="a"></param>
  92. // /// <param name="b"></param>
  93. // /// <returns></returns>
  94. // public static string GetDscString(string a, float[] b)
  95. // {
  96. // if (a == "")
  97. // return "";
  98. // for (int i = 0; i < b?.Length; i++)
  99. // {
  100. // string d = b[i].ToString();
  101. // string c = "{" + i + "}";
  102. // a = a.Replace(c, d);
  103. // }
  104. //
  105. // return a;
  106. // }
  107. /// <summary>
  108. /// 获取描述文本
  109. /// </summary>
  110. /// <param name="a"></param>
  111. /// <param name="b"></param>
  112. /// <returns></returns>
  113. public static string GetDscString(string a, float[] b)
  114. {
  115. if (a == "")
  116. return "";
  117. for (int i = 0; i < b?.Length; i++)
  118. {
  119. string d = b[i].ToString("0.##");
  120. string c = "{" + i + "}";
  121. a = a.Replace(c, d);
  122. }
  123. return a;
  124. }
  125. /// <summary>
  126. /// 获取描述文本
  127. /// </summary>
  128. /// <param name="a"></param>
  129. /// <param name="b"></param>
  130. /// <returns></returns>
  131. public static string GetDscString(string a, string[] b)
  132. {
  133. if (a == "")
  134. return "";
  135. for (int i = 0; i < b?.Length; i++)
  136. {
  137. string d = b[i].ToString();
  138. string c = "{" + i + "}";
  139. a = a.Replace(c, d);
  140. }
  141. return a;
  142. }
  143. public static string GetSignaturesInfo()
  144. {
  145. #if UNITY_ANDROID&&!UNITY_EDITOR
  146. AndroidJavaClass contextClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  147. AndroidJavaObject context = contextClass.GetStatic<AndroidJavaObject>("currentActivity");
  148. AndroidJavaObject packageManager = context.Call<AndroidJavaObject>("getPackageManager");
  149. string packageName = context.Call<string>("getPackageName");
  150. int flags = packageManager.GetStatic<int>("GET_SIGNATURES");
  151. AndroidJavaObject packageInfo =
  152. packageManager.Call<AndroidJavaObject>("getPackageInfo", packageName, flags);
  153. AndroidJavaObject[] signatures = packageInfo.Get<AndroidJavaObject[]>("signatures");
  154. // Get the first signature (assuming only one signature)
  155. AndroidJavaObject signature = signatures[0];
  156. // Convert signature to bytes
  157. byte[] signatureBytes = signature.Call<byte[]>("toByteArray");
  158. // Compute SHA256 hash
  159. SHA256 sha256 = SHA256.Create();
  160. byte[] hashBytes = sha256.ComputeHash(signatureBytes);
  161. // Convert bytes to hex string
  162. StringBuilder builder = new StringBuilder();
  163. for (int i = 0; i < hashBytes.Length; i++)
  164. {
  165. // Debug.Log(hashBytes[i].ToString("x2").ToUpperInvariant());
  166. builder.Append(hashBytes[i].ToString("X2"));
  167. if (i < hashBytes.Length - 1)
  168. {
  169. builder.Append(":");
  170. }
  171. }
  172. string sha256Signature = builder.ToString();
  173. return sha256Signature;
  174. #else
  175. return "";
  176. #endif
  177. }
  178. /// <summary>
  179. /// 正则匹配
  180. /// </summary>
  181. /// <param name="str"></param>
  182. /// <param name="data">"mydata|mydata|"</param>
  183. public static bool MatchingMouna(ref string str, string data)
  184. {
  185. MatchCollection m = Regex.Matches(str, "(" + data + ")", RegexOptions.Multiline);
  186. for (int i = 0; i < m.Count; i++)
  187. {
  188. string m1 = Regex.Replace(m[i].ToString(), "\\$", "\\$");
  189. m1 = Regex.Replace(m1, "\\^", "\\^");
  190. string xingxing = "";
  191. for (int j = 0; j < m1.Length; j++)
  192. xingxing += "*";
  193. str = Regex.Replace(str, m1, xingxing);
  194. }
  195. if (m.Count > 0)
  196. {
  197. return true;
  198. }
  199. else
  200. {
  201. return false;
  202. }
  203. //LogManager.Instance.Log(str + " " + data);
  204. }
  205. /// <summary>
  206. /// 设置对象的层
  207. /// </summary>
  208. /// <param name="layerName"></param>
  209. /// <param name="obj"></param>
  210. /// <param name="isChild"></param>
  211. public static void SetGameObjctLayer(string layerName, GameObject obj, bool isChild = true)
  212. {
  213. int layerIdx = LayerMask.NameToLayer(layerName);
  214. if (isChild)
  215. SetChildLayer(layerIdx, obj.transform);
  216. else
  217. {
  218. obj.layer = layerIdx;
  219. }
  220. }
  221. /// <summary>
  222. /// 设置对象的层
  223. /// </summary>
  224. /// <param name="layerName"></param>
  225. /// <param name="obj"></param>
  226. /// <param name="isChild"></param>
  227. public static void SetGameObjctLayer(int layer, GameObject obj, bool isChild = true)
  228. {
  229. //int layerIdx = LayerMask.NameToLayer(layerName);
  230. if (isChild)
  231. SetChildLayer(layer, obj.transform);
  232. else
  233. {
  234. obj.layer = layer;
  235. }
  236. }
  237. private static void SetChildLayer(int layerIdx, Transform obj)
  238. {
  239. obj.gameObject.layer = layerIdx;
  240. for (int i = 0; i < obj.childCount; i++)
  241. {
  242. SetChildLayer(layerIdx, obj.GetChild(i));
  243. }
  244. }
  245. public static IPEndPoint CombineIPAddress(string host, int port)
  246. {
  247. return new IPEndPoint(IPAddress.Parse(host), port);
  248. }
  249. public static bool IsStringLetterAndNumber(string content)
  250. {
  251. if (content.Length == 0)
  252. {
  253. return false;
  254. }
  255. int asciiCount = Regex.Matches(content, "[a-zA-Z0-9]").Count;
  256. return (content.Length > asciiCount) ? false : true;
  257. }
  258. public static bool IsArrayValid(object array)
  259. {
  260. if (array == null || !(array is Array) || (array as Array).Length == 0)
  261. {
  262. return false;
  263. }
  264. return true;
  265. }
  266. public static Texture2D GetTexture(string path)
  267. {
  268. if (string.IsNullOrEmpty(path))
  269. return null;
  270. if (!File.Exists(path))
  271. return null;
  272. byte[] data = File.ReadAllBytes(path);
  273. Texture2D textrue = new Texture2D(512, 512);
  274. textrue.LoadImage(data);
  275. return textrue;
  276. }
  277. private static string m_bannedWorlds;
  278. public static bool IsBannedWord(string rolename)
  279. {
  280. return false;
  281. }
  282. #if UNITY_EDITOR
  283. /// <summary>
  284. /// 获取场景中全部对象
  285. /// </summary>
  286. /// <typeparam name="T"></typeparam>
  287. /// <returns></returns>
  288. public static List<T> GetAllSceneObj<T>()
  289. {
  290. List<T> ts = new List<T>();
  291. //HierarchyProperty.
  292. //EditorSceneManager.
  293. GameObject[] go = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();
  294. //LogTool.Log(go.Length);
  295. AddObjcet(ts, go);
  296. go = Utility.UtilTools.allDontDestroyOnLoad.ToArray();
  297. AddObjcet(ts, go);
  298. return ts;
  299. }
  300. //public static string GetModelName(GlobalConfig.LevelType _type, MapUnit unit)
  301. //{
  302. // string str =FixationString.empty;
  303. // switch (unit)
  304. // {
  305. // case MapUnit.Wall:
  306. // str = _type.SplitToString() + "_Wall_";
  307. // break;
  308. // case MapUnit.Coin:
  309. // return _type.SplitToString() + "_Seed";
  310. // case MapUnit.Gate:
  311. // return _type.SplitToString() + "_Gate";
  312. // case MapUnit.Player:
  313. // return "Player";
  314. // case MapUnit.WallVisible:
  315. // return _type.SplitToString() + "_WallInvisible";
  316. // case MapUnit.CoinVisible:
  317. // return _type.SplitToString() + "SeedInvisible";
  318. // case MapUnit.BlockLight:
  319. // case MapUnit.BlockBalance:
  320. // case MapUnit.BlockNormal:
  321. // case MapUnit.BlockSleep:
  322. // case MapUnit.BlockGravity:
  323. // return "Block" + _type.SplitToString();
  324. // case MapUnit.Wall_DestroyAble:
  325. // return "Wall_DestroyAble";
  326. // }
  327. // return str;
  328. //}
  329. /// <summary>
  330. private static void AddObjcet<T>(List<T> ts, GameObject[] go)
  331. {
  332. for (int i = 0; i < go.Length; i++)
  333. {
  334. if (!go[i])
  335. continue;
  336. //if (!go[i].gameObject)
  337. // continue;
  338. T[] objs = go[i].transform.GetComponentsInChildren<T>(true);
  339. for (int j = 0; j < objs.Length; j++)
  340. {
  341. ts.Add(objs[j]);
  342. }
  343. }
  344. }
  345. #endif
  346. public static string GetMD5(string inStr)
  347. {
  348. MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
  349. byte[] InBytes = Encoding.UTF8.GetBytes(inStr);
  350. byte[] OutBytes = md5.ComputeHash(InBytes);
  351. string OutString = "";
  352. for (int i = 0; i < OutBytes.Length; i++)
  353. {
  354. OutString += OutBytes[i].ToString("x2");
  355. }
  356. //LogTool.Log(OutString);
  357. if (OutString.Length > 8) OutString = OutString.Substring(0, 8);
  358. return OutString;
  359. }
  360. // DES加密
  361. public static string DESEncrypt(string pToEncrypt, string sKey)
  362. {
  363. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  364. byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
  365. // if (sKey.Length > 8) sKey = sKey.Substring(0, 8);
  366. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  367. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  368. MemoryStream ms = new MemoryStream();
  369. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  370. cs.Write(inputByteArray, 0, inputByteArray.Length);
  371. cs.FlushFinalBlock();
  372. StringBuilder ret = new StringBuilder();
  373. foreach (byte b in ms.ToArray())
  374. {
  375. ret.AppendFormat("{0:X2}", b);
  376. }
  377. ret.ToString();
  378. //LogTool.Log(inputByteArray.Length + " 加密后" + ret.SplitToString().Length);
  379. return ret.ToString();
  380. }
  381. // DES解密
  382. public static string DESDecrypt(string pToDecrypt, string sKey)
  383. {
  384. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  385. byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
  386. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  387. {
  388. int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
  389. inputByteArray[x] = (byte)i;
  390. }
  391. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  392. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  393. MemoryStream ms = new MemoryStream();
  394. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  395. cs.Write(inputByteArray, 0, inputByteArray.Length);
  396. cs.FlushFinalBlock();
  397. StringBuilder ret = new StringBuilder();
  398. return System.Text.Encoding.UTF8.GetString(ms.ToArray());
  399. }
  400. public static string BASE64_Decode(string data)
  401. {
  402. byte[] bytes = Convert.FromBase64String(data);
  403. return Encoding.UTF8.GetString(bytes);
  404. }
  405. public static string GetMD5HashFromFile(byte[] data)
  406. {
  407. try
  408. {
  409. // FileStream file = new FileStream(filename,FileMode.Open);
  410. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  411. byte[] retVal = md5.ComputeHash(data);
  412. StringBuilder sb = new StringBuilder();
  413. for (int i = 0; i < retVal.Length; i++)
  414. {
  415. sb.Append(retVal[i].ToString("x2"));
  416. }
  417. return sb.ToString();
  418. }
  419. catch (System.Exception ex)
  420. {
  421. LogTool.Log("错误信息:" + ex);
  422. return null;
  423. }
  424. }
  425. public static string FormatTwoTime(int totalSeconds)
  426. {
  427. int minutes = totalSeconds / 60;
  428. string mm = minutes < 10f ? "0" + minutes : minutes.ToString();
  429. int seconds = (totalSeconds - (minutes * 60));
  430. string ss = seconds < 10 ? "0" + seconds : seconds.ToString();
  431. return string.Format("{0}:{1}", mm, ss);
  432. }
  433. // public static string ToStringEx(this long i)
  434. // {
  435. // // if (isShowLongEx)
  436. // {
  437. // if (i >= 10000000000)
  438. // return (i / 1000000000) + "B";
  439. // else if (i >= 10000000)
  440. // return (i / 1000000) + "M";
  441. // else if (i >= 10000)
  442. // return (i / 1000) + "K";
  443. // }
  444. //
  445. // return i.ToString();
  446. // }
  447. /// <summary>
  448. /// 获取目标小数位的str
  449. /// </summary>
  450. /// <param name="n"></param>
  451. /// <returns></returns>
  452. public static string GetTargetDecimalPlaceStr(int n)
  453. {
  454. string str = "";
  455. if (n >= 100) //整数大于两位数保留一位小数
  456. {
  457. int n1 = (int)(n * 10);
  458. n = n1 / 10;
  459. str = n.ToString(CultureInfo.InvariantCulture);
  460. }
  461. else
  462. {
  463. //保留两位小数
  464. int n1 = (int)(n * 100);
  465. n = n1 / 100;
  466. str = n.ToString(CultureInfo.InvariantCulture);
  467. }
  468. return str;
  469. }
  470. public static long Round(this float number)
  471. {
  472. return (long)Math.Ceiling(number);
  473. }
  474. /// <summary>
  475. /// 四舍五入到整数
  476. /// </summary>
  477. /// <param name="value"></param>
  478. /// <returns></returns>
  479. public static int RoundToInt(this float value)
  480. {
  481. // float tempValue = value.Round(0);
  482. // int finalValue = Mathf.FloorToInt(tempValue);
  483. Math.Ceiling(value);
  484. return (int)Math.Ceiling(value);
  485. ;
  486. }
  487. public static string ToStringEx(this long number)
  488. {
  489. // if (number > 1000000000000)
  490. // {
  491. // float n = number / 1000000000000f;
  492. // string str = "";
  493. // str = GetTargetDecimalPlaceStr((int)n);
  494. // return str + "t";
  495. // }
  496. //
  497. // if (number > 1000000000)
  498. // {
  499. // float n = number / 1000000000f;
  500. // string str = "";
  501. // str = GetTargetDecimalPlaceStr((int)n);
  502. // return str + "b";
  503. // }
  504. if (number > 1000000)
  505. {
  506. float n = number / 10000f;
  507. string str = "";
  508. str = GetTargetDecimalPlaceStr((int)n);
  509. return str + "m";
  510. }
  511. if (number > 100000)
  512. {
  513. float n = number / 1000f;
  514. string str = "";
  515. str = GetTargetDecimalPlaceStr((int)n);
  516. return str + "k";
  517. }
  518. return number.ToString();
  519. }
  520. public static string ToStringEx(this int number)
  521. {
  522. // if (number > 1000000000000)
  523. // {
  524. // float n = number / 1000000000000f;
  525. // string str = "";
  526. // str = GetTargetDecimalPlaceStr((int)n);
  527. // return str + "t";
  528. // }
  529. //
  530. // if (number > 1000000000)
  531. // {
  532. // float n = number / 1000000000f;
  533. // string str = "";
  534. // str = GetTargetDecimalPlaceStr((int)n);
  535. // return str + "b";
  536. // }
  537. if (number > 1000000)
  538. {
  539. float n = number / 10000f;
  540. string str = "";
  541. str = GetTargetDecimalPlaceStr((int)n);
  542. return str + "m";
  543. }
  544. if (number > 100000)
  545. {
  546. float n = number / 1000f;
  547. string str = "";
  548. str = GetTargetDecimalPlaceStr((int)n);
  549. return str + "k";
  550. }
  551. return number.ToString();
  552. // // if (isShowLongEx)
  553. // {
  554. // if (i >= 10000000000)
  555. // return (i / 1000000000) + "B";
  556. // else if (i >= 10000000)
  557. // return (i / 1000000) + "M";
  558. // else if (i >= 10000)
  559. // return (i / 1000) + "K";
  560. // }
  561. //
  562. // return i.ToString();
  563. }
  564. #endif
  565. /// <summary>
  566. /// 时间(秒)转换位小时分钟秒
  567. /// </summary>
  568. /// <param name="miao"></param>
  569. /// <returns></returns>
  570. public static string TimeToHSM(long miao)
  571. {
  572. long fen = miao / 60;
  573. miao = miao % 60;
  574. long xiaoShi = fen / 60;
  575. long tian = xiaoShi / 24;
  576. xiaoShi = xiaoShi % 24;
  577. fen = fen % 60;
  578. if (tian > 0)
  579. {
  580. return $"{tian}天{xiaoShi}小时";
  581. }
  582. else
  583. {
  584. if (xiaoShi <= 0 && fen <= 59)
  585. {
  586. return $"{fen}分{miao}秒";
  587. }
  588. else
  589. {
  590. return $"{xiaoShi}小时{fen}分";
  591. }
  592. }
  593. }
  594. /// <summary>
  595. /// 时间(秒)转换位小时分钟秒
  596. /// </summary>
  597. /// <param name="miao"></param>
  598. /// <returns></returns>
  599. public static string TimeToHSM1(long miao)
  600. {
  601. long fen = miao / 60;
  602. miao = miao % 60;
  603. long xiaoShi = fen / 60;
  604. long tian = xiaoShi / 24;
  605. xiaoShi = xiaoShi % 24;
  606. fen = fen % 60;
  607. if (tian <= 0 && xiaoShi <= 0)
  608. {
  609. return $"{fen}分钟";
  610. }
  611. else if (tian <= 0 && xiaoShi > 0)
  612. {
  613. return $"{xiaoShi}小时";
  614. }
  615. else if (tian >= 1)
  616. {
  617. return $"{tian}天";
  618. }
  619. return "";
  620. }
  621. public static string GeiLxTime(long miao)
  622. {
  623. long fen = miao / 60;
  624. miao = miao % 60;
  625. long xiaoShi = fen / 60;
  626. long tian = xiaoShi / 24;
  627. xiaoShi = xiaoShi % 24;
  628. fen = fen % 60;
  629. if (tian <= 0 && xiaoShi <= 0)
  630. {
  631. return $"离线{fen}分钟";
  632. }
  633. else if (tian <= 0 && xiaoShi > 0)
  634. {
  635. return $"离线{xiaoShi}小时";
  636. }
  637. else if (tian >= 1 && tian <= 7)
  638. {
  639. return $"离线{tian}天";
  640. }
  641. else if (tian > 7)
  642. {
  643. return "离线七天以上";
  644. }
  645. return "";
  646. }
  647. /// <summary>
  648. /// 类型1 :小于1天后显示分和秒
  649. /// </summary>
  650. /// <param name="miao"></param>
  651. /// <param name="type1"></param>
  652. /// <returns></returns>
  653. public static string TimeToHSM(long miao, int type1)
  654. {
  655. long fen = miao / 60;
  656. miao = miao % 60;
  657. long xiaoShi = fen / 60;
  658. long tian = xiaoShi / 24;
  659. xiaoShi = xiaoShi % 24;
  660. fen = fen % 60;
  661. if (tian > 0)
  662. {
  663. return $"{tian}天{xiaoShi}小时";
  664. }
  665. else
  666. {
  667. string key = "";
  668. switch (type1)
  669. {
  670. case 1:
  671. return $"{fen}分{miao}秒";
  672. break;
  673. default:
  674. break;
  675. }
  676. return key;
  677. }
  678. }
  679. /// <summary>获取秒级别时间戳(10位)</summary>
  680. public static long GetTimestampToSeconds()
  681. {
  682. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  683. return Convert.ToInt64(ts.TotalSeconds);
  684. }
  685. /// <summary>获取毫秒级别时间戳(13位)</summary>
  686. public static long GetTimeStampToMilliseconds()
  687. {
  688. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  689. return Convert.ToInt64(ts.TotalMilliseconds);
  690. }
  691. public static long GetTimestampToSeconds(int value)
  692. {
  693. DateTime dateTime = new DateTime(value, DateTimeKind.Utc);
  694. TimeSpan ts = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  695. return Convert.ToInt64(ts.TotalSeconds);
  696. }
  697. /// <summary>
  698. /// 时间戳转时间结构 秒
  699. /// </summary>
  700. /// <param name="unixTimestamp"></param>
  701. /// <returns></returns>
  702. public static DateTime ConvertUnixTimestamp(double unixTimestamp)
  703. {
  704. DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  705. DateTime convertedTime = unixStartTime.AddSeconds(unixTimestamp).ToLocalTime();
  706. return convertedTime;
  707. }
  708. /// <summary>
  709. ///时间戳转时间结构 毫秒
  710. /// </summary>
  711. /// <param name="unixTimestamp"></param>
  712. /// <returns></returns>
  713. public static DateTime ConvertUnixTimestampForMillis(double unixTimestamp)
  714. {
  715. DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
  716. DateTime convertedTime = unixStartTime.AddMilliseconds(unixTimestamp).ToLocalTime();
  717. return convertedTime;
  718. }
  719. public static string NumberToArab(int number)
  720. {
  721. switch (number)
  722. {
  723. case 0: return "0";
  724. case 1: return "I";
  725. case 2: return "II";
  726. case 3: return "III";
  727. case 4: return "IV";
  728. case 5: return "V";
  729. case 6: return "VI";
  730. }
  731. return "";
  732. }
  733. /// <summary>
  734. /// 获取凌晨时间戳 单位s
  735. /// </summary>
  736. /// <param name="kind"></param>
  737. /// <returns></returns>
  738. public static long GetMidnightTimestamp(DateTimeKind kind = DateTimeKind.Local)
  739. {
  740. DateTime now = DateTime.Now;
  741. DateTime midnight = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0, kind);
  742. DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  743. TimeSpan timeSpan = midnight.ToUniversalTime() - epoch;
  744. return (long)timeSpan.TotalSeconds;
  745. }
  746. public static T DeepCopy<T>(T obj)
  747. {
  748. using (var memoryStream = new MemoryStream())
  749. {
  750. var formatter = new BinaryFormatter();
  751. formatter.Serialize(memoryStream, obj);
  752. memoryStream.Seek(0, SeekOrigin.Begin);
  753. return (T)formatter.Deserialize(memoryStream);
  754. }
  755. }
  756. public static T GetRandomByWeight<T>(List<T> items, int[] weights)
  757. {
  758. if (items.Count != weights.Length)
  759. {
  760. LogTool.Error("权重和数组长度不一致");
  761. }
  762. int totalWeight = weights.Sum();
  763. Random random = new Random();
  764. int randomValue = random.Next(0, totalWeight);
  765. int currentWeight = 0;
  766. for (int i = 0; i < items.Count; i++)
  767. {
  768. currentWeight += weights[i];
  769. if (randomValue < currentWeight)
  770. return items[i];
  771. }
  772. // 理论上不会到达这里,但为了安全返回最后一个元素
  773. return items[items.Count - 1];
  774. }
  775. public static T GetRandomByWeight<T>(List<T> items, float[] weights)
  776. {
  777. if (items.Count != weights.Length)
  778. {
  779. LogTool.Error("权重和数组长度不一致");
  780. }
  781. float totalWeight = weights.Sum();
  782. Random random = new Random();
  783. float randomValue = (float)(random.NextDouble() * totalWeight);
  784. float currentWeight = 0;
  785. for (int i = 0; i < items.Count; i++)
  786. {
  787. currentWeight += weights[i];
  788. if (randomValue < currentWeight)
  789. return items[i];
  790. }
  791. // 理论上不会到达这里,但为了安全返回最后一个元素
  792. return items[items.Count - 1];
  793. }
  794. }
  795. //UtilTools
  796. }