使用javascript时间创建唯一的数字 [英] Create a unique number with javascript time

查看:169
本文介绍了使用javascript时间创建唯一的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javascript动态生成唯一的ID号。在过去,我通过使用时间创建数字来完成此操作。该数字将由四位数年份,两位数月份,两位数日期,两位数小时,两位数分钟,两位数秒和三位数毫秒组成。所以它看起来像这样:20111104103912732 ......这样就可以为我的目的提供足够的确定性。

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.

我做完这个已经有一段时间了我不再有代码了。任何人都有代码来执行此操作,或者有更好的建议来生成唯一ID?

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?

推荐答案

如果您只想要一个唯一的数字,那么

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

这篇关于使用javascript时间创建唯一的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆