using Newtonsoft.Json; using System; namespace YD_AllHeartRates.Commons.Utils { /// /// 工具类 /// public static class Util { /// /// 获取短信Code /// /// public static string GetSmsCode() { Random random = new Random(); return random.Next(1000, 9999).ToString(); } public static string ReplaceWithSpecialChar(string value, int startLen = 4, int endLen = 4, char specialChar = '*') { try { int lenth = value.Length - startLen - endLen; string replaceStr = value.Substring(startLen, lenth); string specialStr = string.Empty; for (int i = 0; i < replaceStr.Length; i++) { specialStr += specialChar; } value = value.Replace(replaceStr, specialStr); } catch (Exception) { throw; } return value; } public static string GetColorValue(string color) { switch (color) { case "黄色": return "#FFFF00"; case "绿色": return "#008000"; case "红色": return "#FF0000"; case "蓝色": return "#0000FF"; default: return "#0000FF"; } } public static string Serialize(this object obj, JsonSerializerSettings formatDate = null) { if (obj == null) return null; formatDate = formatDate ?? new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss" }; return JsonConvert.SerializeObject(obj, formatDate); } public static int GetInt(this object obj) { if (obj == null) return 0; int.TryParse(obj.ToString(), out int _number); return _number; } private static DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0); private static long longTime = 621355968000000000; private static int samllTime = 10000000; /// /// 获取时间戳 /// /// /// public static long GetTimeStamp(this DateTime dateTime) { return (dateTime.ToUniversalTime().Ticks - longTime) / samllTime; } /// /// 时间戳转换成日期 /// /// /// public static DateTime GetTimeSpmpToDate(this object timeStamp) { if (timeStamp == null) return dateStart; DateTime dateTime = new DateTime(longTime + Convert.ToInt64(timeStamp) * samllTime, DateTimeKind.Utc).ToLocalTime(); return dateTime; } public static bool IsNullOrEmpty(this object str) { if (str == null) return true; return str.ToString() == ""; } public static string ConvertSecondsToMinutes(this int? totalSeconds) { if (totalSeconds == null || totalSeconds < 0) return "0分0秒"; int minutes = totalSeconds.Value / 60; int seconds = totalSeconds.Value % 60; return $"{minutes}分{seconds}秒"; } public static int GetRank(this T score) where T : struct, IComparable { // 将 score 转换为 double 进行比较 double value = Convert.ToDouble(score); return value switch { >= 90 => 1, >= 80 => 2, >= 60 => 3, _ => 4 }; } public static string GetRankStr(this T score) where T : struct, IComparable { // 将 score 转换为 double 进行比较 double value = Convert.ToDouble(score); return value switch { >= 90 => "优秀", >= 80 => "良好", >= 60 => "及格", _ => "低分" }; } } }