Search code examples
javascripttimenumbersunique

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?


Solution

  • 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.getMonth < 9 ? '0' : '') + now.getMonth().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()