views:

34

answers:

2

Hello, I'm using the following 2 lines of JS to create a UID:

var UID = dateobj.getTime();
UID = String(UID).substr(4);

It appears that sometimes it generates a number like:
564929300
other times like:
56492930

Problem is the length isn't consistent which is messing things up. Any ideas how that's possible and if there is a way to fix this or a better way to make a UID with JS?

Thanks

+1  A: 

There one implementation here: http://blog.shkedy.com/2007/01/createing-guids-with-client-side.html

Here it is in action: http://jsfiddle.net/7sXL6/

I threw together a smaller version of it: http://jsfiddle.net/7sXL6/4/

Andir
Thanks, that seems like a lot of code for a semi-elegant solution. Thoughts?
AnApprentice
Really all it's doing is generating 32 random characters plus hyphens... there are many ways to do it, but this one fits the mold of a GUID. You could strip out some of the specific formatting if it's not needed. If you wanted to use the time, you'd have to pad zeros to the front to make it a specific length.
Andir
Instead of moving to another so so solution I'm curious, do you know why getTime would be providing a variable length?
AnApprentice
getDate returns the number of milliseconds since midnight, Jan 1, 1970. If one of the clients set their clock to Jan 2, 1970 you will get a very low number. See here: http://jsfiddle.net/7sXL6/3/
Andir
Thanks Is there a way to always make sure it's at least 10 characters?
AnApprentice
You would have to pad zeros to the front of it. See this: http://jsfiddle.net/DwPFA/
Andir
+1  A: 

I like doing Math.random().toString(36).substr(2,9)

antimatter15
That works too ;)
Andir
Very cool, so what exactly is code doing? A little explanation would be cool and probably help tons of people that find this page in the SERPS. thxs
AnApprentice
interesting, problem is it needs to be all integers, no characters. Can that be modified above?
AnApprentice
If you just want integers, you can get rid of the number 36, so it would become Math.random().toString().substr(2,9)In Javascript, when you're converting from a number to a string with .toString(), you can specify a base for conversion. Like (2).toString(2) would return the binary "10", and 36 just means 0123456789abcdefghijklmnopqrstuvwxyz (0-9 + a-z = 36). It can convert fractional parts too. So you end up after the string to something like "0.634k072981xde7b9" and substr(2,9) makes it a nine-letter string ignoring the starting "0.".
antimatter15