Create a unique number with javascript time(使用 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 时间创建一个唯一的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 javascript 时间创建一个唯一的数字


- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01