What is wrong with using DateTime.Now. how is the bulk of the unique identifier?

I used RNGCryptoServiceProvider to create string order identifiers, but there were 4 instances where ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@ $%^*()_- created an existing order identifier.

And that made me think ...

Why can't we just use something like:

 <html> ... <p>@GenerateOrderId()</p> ... </html> 

and

 public string GenerateOrderId() { return "OID" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond; } 

I was told that this was a bad idea, but without any explanation or reason, it was still stuck in my head. ... The reason I would like to use this is because it will always be unique.

+7
source share
6 answers

Computers run in nanoseconds. You are guaranteed to generate a duplicate order ID almost immediately.

It is best to use the GUID [MSDN-C #] [MSDN-SQL] (aka UNIQUEIDENTIFIER in the SQL world).

+19
source

It will not always be unique.

If the same process is performed within the same millisecond, then it will be identical.

As @Bill stated, you should use a GUID for a unique string.

+7
source

Never call the getter Now so many times. "Now" may change when you add lines. You could say DateTime.Now.ToString("yyyyMMddHHmmssfff") or the like, but it's much better to use Guid.NewGuid() for this.

+6
source

If you just want a globally unique identifier and don't worry about the format, why don't you just use a GUID ?

http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx

 using System; class Sample { public static void Main() { Guid g = Guid.NewGuid(); Console.WriteLine(g); } } 

It even has a type in T-SQL (which you can quite use, considering that you are using ASP.NET)

+4
source

I recommend allowing your database to handle this responsibility, but if you must do this in code, use a GUID. GUID has a low probability of duplication.

  public string GenerateOrderId() { return System.Guid.NewGuid().ToString(); } 
+2
source

Don't hit a dead horse, but your use of DateTime.Now is more of a concern than what you are trying to do. You can rewrite your method and achieve the same goal much more succinctly:

 public string GenerateOrderID() { return "OID" + DateTime.Now.Ticks.ToString(); } 

I would still recommend using Guid for this approach. However, 99% of the time, the Ticks property will give you a different number each time it is called.

0
source

All Articles