@@ -29,6 +29,9 @@ public static class UUIDv7
2929 private static UInt16 s_counter = 0 ;
3030 private static readonly Object s_counterLock = new Object ( ) ;
3131
32+ /// <summary>
33+ /// The method of generating the clock sequence and Node ID.
34+ /// </summary>
3235 public enum GenerationMethod
3336 {
3437 /// <summary>
@@ -49,6 +52,7 @@ public enum GenerationMethod
4952 /// <summary>
5053 /// Initialises a new GUID/UUID based on Version 7 (date-time)
5154 /// </summary>
55+ /// <param name="method">The method of generating the clock sequence and Node ID.</param>
5256 /// <returns>A new Uuid object</returns>
5357 public static Uuid NewUUIDv7 ( GenerationMethod method = GenerationMethod . Random )
5458 {
@@ -59,6 +63,7 @@ public static Uuid NewUUIDv7(GenerationMethod method = GenerationMethod.Random)
5963 /// Initialises a new GUID/UUID based on Version 7 (date-time), based on the given date and time.
6064 /// </summary>
6165 /// <param name="dateTime">Given Date and Time</param>
66+ /// <param name="method">The method of generating the clock sequence and Node ID.</param>
6267 /// <returns>A new Uuid object</returns>
6368 public static Uuid NewUUIDv7 ( DateTime dateTime , GenerationMethod method = GenerationMethod . Random )
6469 {
@@ -199,5 +204,45 @@ public static Byte[] GetRandomB()
199204 return fakeNode ;
200205 }
201206 }
207+
208+ /// <summary>
209+ /// Returns true if the Uuid specified is Version 7.
210+ /// </summary>
211+ /// <param name="uuid">The Uuid to be tested.</param>
212+ /// <returns>Returns true if the Uuid specified is Version 7.</returns>
213+ public static bool IsUUIDv7 ( Uuid uuid )
214+ {
215+ return ( uuid . ToByteArray ( ) [ 6 ] >> 4 ) == 0x07 ;
216+ }
217+
218+ /// <summary>
219+ /// Returns the approximate DateTime used to generate the Uuid.
220+ /// </summary>
221+ /// <param name="uuid">The Uuid Version 7 object</param>
222+ /// <returns>DateTime of the Uuid in UTC.</returns>
223+ /// <exception cref="ArgumentException"></exception>
224+ public static DateTime ToDateTime ( Uuid uuid )
225+ {
226+ if ( ! IsUUIDv7 ( uuid ) )
227+ throw new ArgumentException ( String . Format ( "{0} is not a Version 7 UUID." , uuid ) , nameof ( uuid ) ) ;
228+
229+ Byte [ ] time = new Byte [ 8 ] ;
230+ Byte [ ] hex = uuid . ToByteArray ( ) ;
231+
232+ time [ 0 ] = hex [ 0 ] ;
233+ time [ 1 ] = hex [ 1 ] ;
234+ time [ 2 ] = hex [ 2 ] ;
235+ time [ 3 ] = hex [ 3 ] ;
236+ time [ 4 ] = hex [ 4 ] ;
237+ time [ 5 ] = hex [ 5 ] ;
238+ time [ 6 ] = hex [ 6 ] ;
239+ time [ 7 ] = hex [ 7 ] ;
240+
241+ Int64 timeInterval = System . Net . IPAddress . NetworkToHostOrder ( BitConverter . ToInt64 ( time , 0 ) ) ;
242+ timeInterval >>= 16 ;
243+ TimeSpan timeSpan = TimeSpan . FromMilliseconds ( timeInterval ) ;
244+
245+ return s_epoch . ToUniversalTime ( ) + timeSpan ;
246+ }
202247 }
203248}
0 commit comments