码迷,mamicode.com
首页 > 其他好文 > 详细

Guid

时间:2017-11-20 20:15:53      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:summary   cti   tostring   returns   span   turn   ase   bytearray   tco   

#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;
}

Guid

标签:summary   cti   tostring   returns   span   turn   ase   bytearray   tco   

原文地址:http://www.cnblogs.com/ZkbFighting/p/7867838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!