Home  >  Article  >  Daily Programming  >  How to get the current timestamp in JS

How to get the current timestamp in JS

藏色散人
藏色散人Original
2018-12-12 16:57:4626465browse

JS can obtain the current timestamp through the Date.now() method, which returns the number of milliseconds that have passed since January 1, 1970 00:00:00 UTC, which is the current timestamp.

How to get the current timestamp in JS

# Now we will introduce how to get the current timestamp with JS based on specific code examples.

The code example is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS获取当前时间戳的方法示例</title>
</head>
<body>
<script type="text/javascript">
    //创建一个时间戳
    var time = Date.now();
    document.write(time + "<hr>");
</script>

</body>

</html>

Get the current timestamp result as follows:

How to get the current timestamp in JS

The timestamp refers to Greenway The total number of milliseconds from 00:00:00 on January 1, 1970 (08:00:00 on January 1, 1970, Beijing time) to the present.

Date.now() method Returns the number of milliseconds that have elapsed since January 1, 1970 00:00:00 UTC.

The syntax:

var timeInMs = Date.now();

The return value represents the number of milliseconds that have passed since the UNIX epoch.

But the timestamp format should not be easy for most people to understand, so how do we convert it into a time format that everyone is familiar with? It's actually very simple.

The code example is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
<script type="text/javascript">
    //创建一个时间戳
    var time = Date.now();
    //document.write(time + "<hr>");
    //将其转换为人们可读的日期和时间
    var d = new Date(time);
    document.write(d);
</script>
</body>
</html>

The conversion result is as shown below:

How to get the current timestamp in JS

Date object is used to process date and time, new Keywords are used to define Date objects.

Use new Date() in js to convert the timestamp into a human-readable date and time. The format displayed is: week, month, day, year, hour, minute, second, time zone

This article is about JS An introduction to the method of obtaining the current timestamp and converting it to normal time format. It is very simple. I hope it will be helpful to friends in need!

The above is the detailed content of How to get the current timestamp in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn