C# 生成唯一订单号
标签:number ram 时间 生产 str class mes turn 字符
根据GUID+DateTime.Now.Ticks生产唯一订单号
1 ///
2 /// 生成唯一数
3 ///
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 ///
11 /// 生成
12 ///
13 /// 前缀
14 /// 时间精确类型 1 日,2 时,3 分,4 秒(默认)
15 /// id 小于或等于0则随机生成id
16 ///
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 ///
39 /// 生成
40 ///
41 /// 前缀
42 /// 时间精确类型 1 日,2 时,3 分,4 秒(默认)
43 /// id 小于或等于0则随机生成id
44 ///
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 ///
67 /// 获取时间字符串
68 ///
69 /// 时间精确类型 1 日,2 时,3 分,4 秒(默认)
70 /// 填充位数
71 ///
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 }
C# 生成唯一订单号
标签:number ram 时间 生产 str class mes turn 字符
原文地址:https://www.cnblogs.com/ylkbdw/p/9565295.html
评论