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

查看:25
本文介绍了使用 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.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()

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

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