/// <summary> /// 生成全局唯一32位字符串Id /// </summary> /// <returns></returns> public static string NewId() { DateTime now = DateTime.Now; if (now.Year > MaxYear) { throw new InvalidOperationException($"Current year can't be greater than {MaxYear}"); } // 使用31进制计算,值不会超过3个字节 int td = now.Year * 31 * 31 + now.Month * 31 + now.Day; // 4个字节,最后一个字节为0 byte[] bs4 = BitConverter.GetBytes(td); // 取3个非0字节 byte[] bs3 = new byte[3]; Array.Copy(bs4, bs3, 3); // 年月日部分编码后,5个字符 string ymd = OrderBase32.ToBase32(bs3); // 小时部分 char h = NumberCharDic[now.Hour]; // Guid部分,26个字符 string guid = OrderBase32.ToBase32(Guid.NewGuid().ToByteArray()); StringBuilder sb = new StringBuilder(32); sb.Append(ymd).Append(h).Append(guid); return(sb.ToString()); }
/// <summary> /// 生成全局唯一32位字符串Id /// </summary> /// <returns></returns> public static string NewId2() { DateTime now = DateTime.Now; if (now.Year > MaxYear) { throw new InvalidOperationException($"Current year can't be greater than {9999}"); } // 4个字符 string year = now.Year.ToString().PadLeft(4, '0'); char month = NumberCharDic[now.Month]; char day = NumberCharDic[now.Day]; // Guid部分,26个字符 string guid = OrderBase32.ToBase32(Guid.NewGuid().ToByteArray()); StringBuilder sb = new StringBuilder(32); sb.Append(year).Append(month).Append(day).Append(guid); return(sb.ToString()); }