我想要一个表示当前日期和时间的数字,比如Unix时间戳。
当前回答
在JavaScript中获取时间戳
在JavaScript中,时间戳是自1970年1月1日以来经过的毫秒数。如果您不打算支持<IE8,可以使用
new Date().getTime(); + new Date(); and Date.now();
直接获取时间戳,而无需创建新的Date对象。
返回所需的时间戳
new Date("11/01/2018").getTime()
其他回答
这似乎奏效了。
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
有很多方法可以做到这一点。
Date.now()
new Date().getTime()
new Date().valueOf()
要获取以秒为单位的时间戳,请使用以下方法进行转换:
Math.floor(Date.now() / 1000)
我强烈建议使用moment.js
moment().valueOf()
要获取自UNIX纪元以来的秒数,请执行
moment().unix()
也可以这样转换时间:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
我一直这么做。没有双关语。
要在浏览器中使用moment.js:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
有关更多详细信息,包括安装和使用MomentJS的其他方式,请参阅他们的文档
JavaScript的工作时间是从纪元开始的毫秒数,而大多数其他语言的工作时间都是秒。您可以使用毫秒来工作,但只要您传递一个值来表示PHP,PHP本机函数可能就会失败。所以,为了确保我总是使用秒,而不是毫秒。
这将为您提供Unix时间戳(以秒为单位):
var unix = Math.round(+new Date()/1000);
这将为您提供自纪元以来的毫秒数(而不是Unix时间戳):
var milliseconds = new Date().getTime();
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
推荐文章
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- 在Android应用程序中显示当前时间和日期
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何转换日期时间?将日期时间
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?