javascript getTime() 只能到 10 位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13242828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript getTime() to 10 digits only
提问by weyhei
I am using the following function to get the Time using javascript:
我正在使用以下函数来使用 javascript 获取时间:
function timeMil(){
var date = new Date();
var timeMil = date.getTime();
return timeMil;
}
And the value I get is:
我得到的价值是:
1352162391299
1352162391299
While in PHP, I use the time();
function to get Time and the value I get is
在 PHP 中,我使用time();
函数来获取时间,我得到的值是
1352162391
How do I convert the value of javascript time to remove the last 3 digits and make it 10 digits only.
如何转换 javascript time 的值以删除最后 3 位数字并使其仅为 10 位数字。
From 1352162391299
To 1352162391
So that the Javascript time is the same with the PHP time.
从 1352162391299
到 1352162391
这样Javascript时间和PHP时间是一样的。
回答by Kirill Ivlev
I think you just have to divide it by 1000 milliseconds and you'll get time in seconds
我认为你只需将它除以 1000 毫秒,你就会得到以秒为单位的时间
Math.floor(date.getTime()/1000)
回答by RobG
If brevity is ok, then:
如果简洁没有问题,那么:
function secondsSinceEpoch() {
return new Date/1000 | 0;
}
Where:
在哪里:
new Date
is equivalent tonew Date()
| 0
truncates the decimal part of the result and is equivalent toMath.floor(new Date/1000)
(see What does |0 do in javascript).
new Date
相当于new Date()
| 0
截断结果的小数部分并等效于Math.floor(new Date/1000)
(请参阅|0 在 javascript 中做什么)。
Using newer features, and allowing for a Date to be passed to the function, the code can be reduced to:
使用更新的功能,并允许将日期传递给函数,代码可以简化为:
let getSecondsSinceEpoch = (x = new Date) => x/1000 | 0;
But I prefer function declarations as I think they're clearer.
但我更喜欢函数声明,因为我认为它们更清晰。
回答by Nayan Patel
Try dividing it by 1000, and use parseInt method.
尝试将其除以 1000,并使用 parseInt 方法。
const t = parseInt(Date.now()/1000);
console.log(t);
回答by JCOC611
You could divide by 1000 and use Math.floor()
on JavaScript.
您可以除以 1000 并Math.floor()
在 JavaScript 上使用。