JavaScript获取时间戳的三个方法:
- Date.parse(new Date())
获取13位时间戳,例如1553581293000, - (new Date()).valueOf()
获取13位时间戳,精确到毫秒,例如:1553581461549 - new Date().getTime()。
获取13位时间戳,精确到毫秒,例如:1553581482325
示例
以上面第一种方法为例
<!DOCTYPE html>
<html>
<body>
<p id="demo">timestamp</p>
<button type="button" onclick="myFunction()">点击这里,显示时间戳</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date.parse(new Date());
}
</script>
</body>
</html>
上述页面中的脚本执行后,会返回13位数字,如:1553581461549。parse
方法会解析包含日期的字符串,并返回该日期与1970年1月1日午夜之间的毫秒数(UTC
时间)。而上面parse
解析的字符串是通过new Date()
方法来获取到的,从下面的内容来看,new Date()
获取的是一个当前主机的本地时间。
/** Enables basic storage and retrieval of dates and times. */
interface Date {
/** Returns a string representation of a date. The format of the string depends on the locale. */
toString(): string;
/** Returns a date as a string value. */
toDateString(): string;
/** Returns a time as a string value. */
toTimeString(): string;
/** Returns a value as a string value appropriate to the host environment's current locale. */
toLocaleString(): string;
/** Returns a date as a string value appropriate to the host environment's current locale. */
toLocaleDateString(): string;
/** Returns a time as a string value appropriate to the host environment's current locale. */
toLocaleTimeString(): string;
/** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
valueOf(): number;
/** Gets the time value in milliseconds. */
getTime(): number;
/** Gets the year, using local time. */
getFullYear(): number;
/** Gets the year using Universal Coordinated Time (UTC). */
getUTCFullYear(): number;
/** Gets the month, using local time. */
getMonth(): number;