Create a unique number with javascript time

后端 未结 30 3189
生来不讨喜
生来不讨喜 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 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();
    

提交回复
热议问题