Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Created October 24, 2016 19:24
Show Gist options
  • Save DamianSuess/0e43fbc4f1606434816454dcf887ee0d to your computer and use it in GitHub Desktop.
Save DamianSuess/0e43fbc4f1606434816454dcf887ee0d to your computer and use it in GitHub Desktop.
Db-CombinedGuid
//
// Used to create a Combined GUID for database Primary Keys
//
public Guid GenerateComb()
{
// T-SQL Equivalent
// DECLARE @guid UNIQUEIDENTIFIER;
// SET @guid = CAST(CAST(NEWID() AS BINARY(10)) + CAST(GETDATE() AS BINARY(6)) AS UNIQUEIDENTIFIER);
// SELECT @guid;
byte[] destinationArray = Guid.NewGuid().ToByteArray();
DateTime time = new DateTime(0x76c, 1, 1);
DateTime now = DateTime.Now;
TimeSpan span = new TimeSpan(now.Ticks - time.Ticks);
TimeSpan timeOfDay = now.TimeOfDay;
byte[] bytes = BitConverter.GetBytes(span.Days);
byte[] array = BitConverter.GetBytes((long) (timeOfDay.TotalMilliseconds / 3.333333));
Array.Reverse(bytes);
Array.Reverse(array);
Array.Copy(bytes, bytes.Length - 2, destinationArray, destinationArray.Length - 6, 2);
Array.Copy(array, array.Length - 4, destinationArray, destinationArray.Length - 4, 4);
return new Guid(destinationArray);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment