C#根据时间产生有序的GUID编码

public static Guid GenerateGuid()
{
    byte[] guidArray = Guid.NewGuid().ToByteArray();

    var baseDate = new DateTime(1900, 1, 1);
    DateTime now = DateTime.Now;
    var days = new TimeSpan(now.Ticks - baseDate.Ticks);
    TimeSpan msecs = now.TimeOfDay;

    byte[] daysArray = BitConverter.GetBytes(days.Days);
    byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));

    Array.Reverse(daysArray);
    Array.Reverse(msecsArray);

    Array.Copy(daysArray,daysArray.Length - 2,guidArray,guidArray.Length - 6,2);
    Array.Copy(msecsArray,msecsArray.Length - 4,guidArray,guidArray.Length - 4,4);

    return new Guid(guidArray);
}

 

public static Guid GenerateGuid()
{
    byte[] guidArray = Guid.NewGuid().ToByteArray();
 
    var baseDate = new DateTime(1900, 1, 1);
    DateTime now = DateTime.Now;
    var days = new TimeSpan(now.Ticks - baseDate.Ticks);
    TimeSpan msecs = now.TimeOfDay;
 
    byte[] daysArray = BitConverter.GetBytes(days.Days);
    byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));
 
    Array.Reverse(daysArray);
    Array.Reverse(msecsArray);
 
    Array.Copy(daysArray,daysArray.Length - 2,guidArray,guidArray.Length - 6,2);
    Array.Copy(msecsArray,msecsArray.Length - 4,guidArray,guidArray.Length - 4,4);
 
    return new Guid(guidArray);
}

 

posted @ 2016-07-20 22:57  shiningrise  阅读(2941)  评论(1编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css