方法:使用13位的当前时间的时间戳,在加上几个随机数
public static string GetTimestamp()
{
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间
//随机数
string strRandomResult = NextRandom(1000, 1).ToString();
string randonTime=(long)ts.TotalMilliseconds+ strRandomResult;//13位当前时间戳+4位随机数
return randonTime;
}
public static int NextRandom(int numSeeds, int length)
{
// Create a byte array to hold the random value.
byte[] randomNumber = new byte[length];
// Create a new instance of the RNGCryptoServiceProvider.
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
// Fill the array with a random value.
rng.GetBytes(randomNumber);
// Convert the byte to an uint value to make the modulus operation easier.
uint randomResult = 0x0;
for (int i = 0; i<length; i++)
{
randomResult |= ((uint) randomNumber[i] << ((length - 1 - i) * 8));
}
return (int) (randomResult % numSeeds) + 1;
}
运行结果(最后三位为随机数):

本文介绍了一种利用13位时间戳结合随机数在C#中生成18位以内唯一纯数字的方法,确保ID的独特性。
12万+

被折叠的 条评论
为什么被折叠?



