Guid

it2026-08-29  18

#region 生成ID

public static string CreateGuid(int index) { //CAST(CAST(NEWID() AS BINARY(10)) + CAST(GETDATE() AS BINARY(6)) AS UNIQUEIDENTIFIER) byte[] guidArray = Guid.NewGuid().ToByteArray(); DateTime now = DateTime.Now;

DateTime baseDate = new DateTime(1900, 1, 1);

TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);

TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks)); byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long)((msecs.TotalMilliseconds + index * 10) / 3.333333));

Array.Copy(daysArray, 0, guidArray, 2, 2); //毫秒高位 Array.Copy(msecsArray, 2, guidArray, 0, 2); //毫秒低位 Array.Copy(msecsArray, 0, guidArray, 4, 2); return new System.Guid(guidArray).ToString(); }

/// <summary> /// 创建一个按时间排序的Guid /// </summary> /// <returns></returns> public static string CreateGuid() { //CAST(CAST(NEWID() AS BINARY(10)) + CAST(GETDATE() AS BINARY(6)) AS UNIQUEIDENTIFIER) byte[] guidArray = Guid.NewGuid().ToByteArray(); DateTime now = DateTime.Now;

DateTime baseDate = new DateTime(1900, 1, 1);

TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);

TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks)); byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));

Array.Copy(daysArray, 0, guidArray, 2, 2); //毫秒高位 Array.Copy(msecsArray, 2, guidArray, 0, 2); //毫秒低位 Array.Copy(msecsArray, 0, guidArray, 4, 2); return new System.Guid(guidArray).ToString(); }

public static DateTime GetDateTimeFromGuid(string strGuid) { Guid guid = Guid.Parse(strGuid);

DateTime baseDate = new DateTime(1900, 1, 1); byte[] daysArray = new byte[4]; byte[] msecsArray = new byte[4]; byte[] guidArray = guid.ToByteArray();

// Copy the date parts of the guid to the respective byte arrays. Array.Copy(guidArray, guidArray.Length - 6, daysArray, 2, 2); Array.Copy(guidArray, guidArray.Length - 4, msecsArray, 0, 4);

// Reverse the arrays to put them into the appropriate order Array.Reverse(daysArray); Array.Reverse(msecsArray);

// Convert the bytes to ints int days = BitConverter.ToInt32(daysArray, 0); int msecs = BitConverter.ToInt32(msecsArray, 0);

DateTime date = baseDate.AddDays(days); date = date.AddMilliseconds(msecs * 3.333333);

return date; }

转载于:https://www.cnblogs.com/ZkbFighting/p/7867838.html

相关资源:GUID生成器 GUID生成小程序
最新回复(0)