我如何获得当前日期或/和时间在秒使用Javascript?


当前回答

要获得今天的总秒数:

getTodaysTotalSeconds(){
    let date = new Date();        
    return +(date.getHours() * 60 * 60) + (date.getMinutes() * 60) + date.getSeconds();
}

我在return中使用了add +它在int中返回。这可能对其他开发人员有所帮助。:)

其他回答

根据你的评论,我认为你在寻找这样的东西:

var timeout = new Date().getTime() + 15*60*1000; //add 15 minutes;

然后在你的检查中,你在检查:

if(new Date().getTime() > timeout) {
  alert("Session has expired");
}
Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000

这应该会给出从一天开始算起的毫秒数。

(Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000)/1000

这应该会给你一些时间。

(Date.now()-(Date.now()/1000/60/60/24|0)*24*60*60*1000)/1000

与前面相同,只是使用了位运算符来计算天数的下限。

//当前Unix时间戳 // 1443535752秒自1970年1月1日。(UTC) //当前时间,单位为秒 console.log(数学。floor(new Date().valueOf() / 1000));/ / 1443535752 console.log(Math.floor(Date.now() / 1000));/ / 1443535752 console.log(数学。floor(new Date().getTime() / 1000));/ / 1443535752 < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>

jQuery

console.log(Math.floor($.now() / 1000));/ / 1443535752 < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>

这些JavaScript解决方案提供了从1970年1月1日午夜开始的毫秒或秒。

IE 9+解决方案(IE 8或旧版本不支持):

var timestampInMilliseconds = Date.now();
var timestampInSeconds = Date.now() / 1000; // A float value; not an integer.
    timestampInSeconds = Math.floor(Date.now() / 1000); // Floor it to get the seconds.
    timestampInSeconds = Date.now() / 1000 | 0; // Also you can do floor it like this.
    timestampInSeconds = Math.round(Date.now() / 1000); // Round it to get the seconds.

要获得有关Date.now()的更多信息,请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

通用解决方案:

// ‘+’ operator makes the operand numeric.
// And ‘new’ operator can be used without the arguments ‘(……)’.
var timestampInMilliseconds = +new Date;
var timestampInSeconds = +new Date / 1000; // A float value; not an intger.
    timestampInSeconds = Math.floor(+new Date / 1000); // Floor it to get the seconds.
    timestampInSeconds = +new Date / 1000 | 0; // Also you can do floor it like this.
    timestampInSeconds = Math.round(+new Date / 1000); // Round it to get the seconds.

如果你不想要这种情况,请小心使用。

if(1000000 < Math.round(1000000.2)) // false.

如果你只是在THREE JS中需要几秒钟,使用下面的代码中的一个在函数uses window.requestAnimationFrame()

let sec = parseInt(Date.now().toString()[10]);console.log('计数秒=> '+秒);

或 let currentTime= Date.now();

let secAsString= time.toString()[10];

let sec = parseInt(t);

console.log('计数秒=>'+秒);