Create a unique number with javascript time

后端 未结 30 2979
生来不讨喜
生来不讨喜 2020-12-02 08:31

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 digi

相关标签:
30条回答
  • 2020-12-02 08:57

    simple solution I found

    var today = new Date().valueOf();

    console.log( today );

    0 讨论(0)
  • 2020-12-02 08:58

    This also should do:

    (function() {
        var uniquePrevious = 0;
        uniqueId = function() {
            return uniquePrevious++;
        };
    }());
    
    0 讨论(0)
  • 2020-12-02 08:59

    This should do :

    var uniqueNumber = new Date().getTime(); // milliseconds since 1st Jan. 1970
    
    0 讨论(0)
  • 2020-12-02 08:59

    Since milliseconds are not updated every millisecond in node, following is an answer. This generates a unique human readable ticket number. I am new to programming and nodejs. Please correct me if I am wrong.

    function get2Digit(value) {
    if (value.length == 1) return "0" + "" + value;
    else return value;
    

    }

    function get3Digit(value) {
    if (value.length == 1) return "00" + "" + value;
    else return value;
    

    }

    function generateID() {
        var d = new Date();
        var year = d.getFullYear();
        var month = get2Digit(d.getMonth() + 1);
        var date = get2Digit(d.getDate());
        var hours = get2Digit(d.getHours());
        var minutes = get2Digit(d.getMinutes());
        var seconds = get2Digit(d.getSeconds());
        var millSeconds = get2Digit(d.getMilliseconds());
        var dateValue = year + "" + month + "" + date;
        var uniqueID = hours + "" + minutes + "" + seconds + "" + millSeconds;
    
        if (lastUniqueID == "false" || lastUniqueID < uniqueID) lastUniqueID = uniqueID;
        else lastUniqueID = Number(lastUniqueID) + 1;
        return dateValue + "" + lastUniqueID;
    }
    
    0 讨论(0)
  • 2020-12-02 08:59

    Assumed that the solution proposed by @abarber it's a good solution because uses (new Date()).getTime() so it has a windows of milliseconds and sum a tick in case of collisions in this interval, we could consider to use built-in as we can clearly see here in action:

    Fist we can see here how there can be collisions in the 1/1000 window frame using (new Date()).getTime():

    console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
    VM1155:1 1469615396590
    VM1155:1 1469615396591
    console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
    VM1156:1 1469615398845
    VM1156:1 1469615398846
    console.log( (new Date()).getTime() ); console.log( (new Date()).getTime() )
    VM1158:1 1469615403045
    VM1158:1 1469615403045
    

    Second we try the proposed solution that avoid collisions in the 1/1000 window:

    console.log( window.mwUnique.getUniqueID() ); console.log( window.mwUnique.getUniqueID() ); 
    VM1159:1 14696154132130
    VM1159:1 14696154132131
    

    That said we could consider to use functions like the node process.nextTick that is called in the event loop as a single tick and it's well explained here. Of course in the browser there is no process.nextTick so we have to figure how how to do that. This implementation will install a nextTick function in the browser using the most closer functions to the I/O in the browser that are setTimeout(fnc,0), setImmediate(fnc), window.requestAnimationFrame. As suggested here we could add the window.postMessage, but I leave this to the reader since it needs a addEventListener as well. I have modified the original module versions to keep it simpler here:

    getUniqueID = (c => {
     if(typeof(nextTick)=='undefined')
    nextTick = (function(window, prefixes, i, p, fnc) {
        while (!fnc && i < prefixes.length) {
            fnc = window[prefixes[i++] + 'equestAnimationFrame'];
        }
        return (fnc && fnc.bind(window)) || window.setImmediate || function(fnc) {window.setTimeout(fnc, 0);};
    })(window, 'r webkitR mozR msR oR'.split(' '), 0);
     nextTick(() => {
       return c( (new Date()).getTime() )  
     })
    })
    

    So we have in the 1/1000 window:

    getUniqueID(function(c) { console.log(c); });getUniqueID(function(c) { console.log(c); });
    undefined
    VM1160:1 1469615416965
    VM1160:1 1469615416966
    
    0 讨论(0)
  • 2020-12-02 09:03

    Maybe even better would be to use getTime() or valueOf(), but this way it returns unique plus human understandable number (representing date and time):

    window.getUniqNr = function() {
      var now = new Date(); 
      if (typeof window.uniqCounter === 'undefined') window.uniqCounter = 0; 
      window.uniqCounter++; 
      var m = now.getMonth(); var d = now.getDay(); 
      var h = now.getHours(); var i = now.getMinutes(); 
      var s = now.getSeconds(); var ms = now.getMilliseconds();
      timestamp = now.getFullYear().toString() 
      + (m <= 9 ? '0' : '') + m.toString()
      +( d <= 9 ? '0' : '') + d.toString() 
      + (h <= 9 ? '0' : '') + h.toString() 
      + (i <= 9 ? '0' : '') + i.toString() 
      + (s <= 9 ? '0' : '') + s.toString() 
      + (ms <= 9 ? '00' : (ms <= 99 ? '0' : '')) + ms.toString() 
      + window.uniqCounter; 
    
      return timestamp;
    };
    window.getUniqNr();
    
    0 讨论(0)
提交回复
热议问题