18

I must generate unique hash - maybe from timestamp. hash must have max 8 chars. How to do it?

For now I have only timestamp:

var t = new Date().getTime();
Nips
  • 13,162
  • 23
  • 65
  • 103
  • You'll have to use some library to generate hash. You can try this: https://code.google.com/p/crypto-js/ – Vivek Sep 18 '15 at 10:28
  • [Related: Generate an 8 character hash from an integer](http://stackoverflow.com/questions/2520794/php-generate-an-8-character-hash-from-an-integer) – rgajrawala Sep 18 '15 at 10:30
  • possible duplicate of [Create GUID / UUID in JavaScript?](http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript) – Limnic Sep 18 '15 at 10:30

1 Answers1

63

That may look funny but the following code may work well for the next couple of centuries :)

(+new Date).toString(36);  // "iepii89m"

After that you can extend it with slicing method: (+new Date).toString(36).slice(-8).

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 2
    And if you wish to minimize the possibility of collision you can try this: `((+new Date) + Math.random()* 100).toString(32)` – Daniel Sokolowski Nov 08 '16 at 15:41
  • 10
    @DanielSokolowski Why would it help in minimising the possibility of collision? I'd argue that it's exactly the opposite. – Michal Sep 20 '17 at 14:11
  • 2
    can you explain what is that + for, very curious – BardZH Dec 12 '19 at 02:18
  • 3
    @Bardia This is basically a shortcut for `Number(new Date).toString(36)`. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus. – VisioN Dec 12 '19 at 10:08
  • 3
    Date.now().toString(36) i think this is prettier – Crusader Jul 22 '20 at 12:29
  • 2
    Great answer here! There's a lot of scenarios where you don't really need UUID but need a unique string based off the progression of time. – Matt Lo Sep 03 '22 at 21:52