Create a unique number with javascript time

后端 未结 30 3160
生来不讨喜
生来不讨喜 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:52

    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()
    

提交回复
热议问题