本文实例为大家分享了C#生成唯一订单号的具体代码,供大家参考,具体内容如下
根据GUID+DateTime.Now.Ticks生产唯一订单号
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
/// <summary>
/// 生成唯一数
/// </summary>
public class UniqueData
{
private static object obj = new object ();
private static int GuidInt { get { return Guid.NewGuid().GetHashCode(); } }
private static string GuidIntStr { get { return Math.Abs(GuidInt).ToString(); } }
/// <summary>
/// 生成
/// </summary>
/// <param name="mark">前缀</param>
/// <param name="timeType">时间精确类型 1 日,2 时,3 分,4 秒(默认) </param>
/// <param name="id">id 小于或等于0则随机生成id</param>
/// <returns></returns>
public static string Gener( string mark, int timeType = 4, int id = 0)
{
lock (obj)
{
var number = mark;
var ticks = (DateTime.Now.Ticks - GuidInt).ToString();
int fillCount = 0; //填充位数
number += GetTimeStr(timeType, out fillCount);
if (id > 0)
{
number += ticks.Substring(ticks.Length - (fillCount + 3)) + id.ToString().PadLeft(10, '0' );
}
else
{
number += ticks.Substring(ticks.Length - (fillCount + 3)) + GuidIntStr.PadLeft(10, '0' );
}
return number;
}
}
/// <summary>
/// 生成
/// </summary>
/// <param name="mark">前缀</param>
/// <param name="timeType">时间精确类型 1 日,2 时,3 分,4 秒(默认)</param>
/// <param name="id">id 小于或等于0则随机生成id</param>
/// <returns></returns>
public static string GenerLong( string mark, int timeType = 4, long id = 0)
{
lock (obj)
{
var number = mark;
var ticks = (DateTime.Now.Ticks - GuidInt).ToString();
int fillCount = 0; //填充位数
number += GetTimeStr(timeType, out fillCount);
if (id > 0)
{
number += ticks.Substring(ticks.Length - fillCount) + id.ToString().PadLeft(19, '0' );
}
else
{
number += GuidIntStr.PadLeft(10, '0' ) + ticks.Substring(ticks.Length - (9 + fillCount));
}
return number;
}
}
/// <summary>
/// 获取时间字符串
/// </summary>
/// <param name="timeType">时间精确类型 1 日,2 时,3 分,4 秒(默认)</param>
/// <param name="fillCount">填充位数</param>
/// <returns></returns>
private static string GetTimeStr( int timeType, out int fillCount)
{
var time = DateTime.Now;
if (timeType == 1)
{
fillCount = 6;
return time.ToString( "yyyyMMdd" );
}
else if (timeType == 2)
{
fillCount = 4;
return time.ToString( "yyyyMMddHH" );
}
else if (timeType == 3)
{
fillCount = 2;
return time.ToString( "yyyyMMddHHmm" );
}
else
{
fillCount = 0;
return time.ToString( "yyyyMMddHHmmss" );
}
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/ylkbdw/archive/2018/08/31/9565295.html