UtilTools.cs 29 KB

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