현재 날짜 / 시간을 초 단위로 가져옵니다 현재 날짜 /

Javascript에서 현재 날짜 / 시간을 초 단위로 가져 오려면 어떻게합니까?



답변

var seconds = new Date().getTime() / 1000;

…. 1970 년 1 월 1 일 자정 이후의 초를 알려줍니다.

참고


답변

 Date.now()

에포크 이후 밀리 초를 제공합니다. 사용할 필요가 없습니다 new.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now 에서 참조를 확인하십시오.

(IE8에서는 지원되지 않습니다.)


답변

new Date().getTime() / 1000부동 소수점 단위로 타임 스탬프를 생성하므로 초를 얻는 데 불완전한 솔루션을 사용하는 것이 좋습니다.

const timestamp = new Date() / 1000; // 1405792936.933
// Technically, .933 would be milliseconds. 

더 나은 해결책은 다음과 같습니다.

// Rounds the value
const timestamp = Math.round(new Date() / 1000); // 1405792937

// - OR -

// Floors the value
const timestamp = new Date() / 1000 | 0; // 1405792936

부동 소수점이없는 값은 부동 소수점이 원하지 않는 결과를 생성 할 수 있으므로 조건문에 더 안전합니다. float로 얻은 입도는 필요 이상일 수 있습니다.

if (1405792936.993 < 1405792937) // true


답변

귀하의 의견을 바탕으로 다음과 같은 것을 찾고 있다고 생각합니다.

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

그런 다음 확인에서 다음을 확인합니다.

if(new Date().getTime() > timeout) {
  alert("Session has expired");
}


답변

Javascript 시대에서 초 수를 얻으려면 다음을 사용하십시오.

date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;


답변

// The Current Unix Timestamp
// 1443535752 seconds since Jan 01 1970. (UTC)

// Current time in seconds
console.log(Math.floor(new Date().valueOf() / 1000));  // 1443535752
console.log(Math.floor(Date.now() / 1000));            // 1443535752
console.log(Math.floor(new Date().getTime() / 1000));  // 1443535752
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery

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


답변

이 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.