Nick Petrie Nick Petrie - 1 year ago 85
Javascript Question

Create a unique number with javascript time

I need to generate unique id numbers on the fly using javascript. In the past, I've done this by creating a number using time. The number would be made up of the four digit year, two digit month, two digit day, two digit hour, two digit minute, two digit second, and three digit millisecond. So it would look something like this: 20111104103912732 ... this would give enough certainty of a unique number for my purposes.

It's been a while since I've done this and I don't have the code anymore. Anyone have the code to do this, or have a better suggestion for generating a unique ID?

Answer Source

If you just want a unique-ish number, then

var timestamp = new Date().getUTCMilliseconds();

would get you a simple number. But if you need the readable version, you're in for a bit of processing:

var now = new Date();

timestamp = now.getFullYear().toString(); // 2011
timestamp += (now.getFullMonth < 9 ? '0' : '') + now.getFullMonth().toString(); // JS months are 0-based, so +1 and pad with 0's
timestamp += (now.getDate < 10) ? '0' : '') + now.getDate().toString(); // pad with a 0
... etc... with .getHours(), getMinutes(), getSeconds(), getMilliseconds()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download