根據GUID+DateTime.Now.Ticks生產唯一訂單號 ...
根據GUID+DateTime.Now.Ticks生產唯一訂單號
1 /// <summary> 2 /// 生成唯一數 3 /// </summary> 4 public class UniqueData 5 { 6 private static object obj = new object(); 7 private static int GuidInt { get { return Guid.NewGuid().GetHashCode(); } } 8 private static string GuidIntStr { get { return Math.Abs(GuidInt).ToString(); } } 9 10 /// <summary> 11 /// 生成 12 /// </summary> 13 /// <param name="mark">首碼</param> 14 /// <param name="timeType">時間精確類型 1 日,2 時,3 分,4 秒(預設) </param> 15 /// <param name="id">id 小於或等於0則隨機生成id</param> 16 /// <returns></returns> 17 public static string Gener(string mark, int timeType = 4, int id = 0) 18 { 19 lock (obj) 20 { 21 var number = mark; 22 var ticks = (DateTime.Now.Ticks - GuidInt).ToString(); 23 int fillCount = 0;//填充位數 24 25 number += GetTimeStr(timeType, out fillCount); 26 if (id > 0) 27 { 28 number += ticks.Substring(ticks.Length - (fillCount + 3)) + id.ToString().PadLeft(10, '0'); 29 } 30 else 31 { 32 number += ticks.Substring(ticks.Length - (fillCount + 3)) + GuidIntStr.PadLeft(10, '0'); 33 } 34 return number; 35 } 36 } 37 38 /// <summary> 39 /// 生成 40 /// </summary> 41 /// <param name="mark">首碼</param> 42 /// <param name="timeType">時間精確類型 1 日,2 時,3 分,4 秒(預設)</param> 43 /// <param name="id">id 小於或等於0則隨機生成id</param> 44 /// <returns></returns> 45 public static string GenerLong(string mark, int timeType = 4, long id = 0) 46 { 47 lock (obj) 48 { 49 var number = mark; 50 var ticks = (DateTime.Now.Ticks - GuidInt).ToString(); 51 int fillCount = 0;//填充位數 52 53 number += GetTimeStr(timeType, out fillCount); 54 if (id > 0) 55 { 56 number += ticks.Substring(ticks.Length - fillCount) + id.ToString().PadLeft(19, '0'); 57 } 58 else 59 { 60 number += GuidIntStr.PadLeft(10, '0') + ticks.Substring(ticks.Length - (9 + fillCount)); 61 } 62 return number; 63 } 64 } 65 66 /// <summary> 67 /// 獲取時間字元串 68 /// </summary> 69 /// <param name="timeType">時間精確類型 1 日,2 時,3 分,4 秒(預設)</param> 70 /// <param name="fillCount">填充位數</param> 71 /// <returns></returns> 72 private static string GetTimeStr(int timeType, out int fillCount) 73 { 74 var time = DateTime.Now; 75 if (timeType == 1) 76 { 77 fillCount = 6; 78 return time.ToString("yyyyMMdd"); 79 } 80 else if (timeType == 2) 81 { 82 fillCount = 4; 83 return time.ToString("yyyyMMddHH"); 84 } 85 else if (timeType == 3) 86 { 87 fillCount = 2; 88 return time.ToString("yyyyMMddHHmm"); 89 } 90 else 91 { 92 fillCount = 0; 93 return time.ToString("yyyyMMddHHmmss"); 94 } 95 } 96 }