Javascript get current time, with getting it in milliseconds and current date

Lionsure 2020-06-30 Original by the website

Sometimes you need to use javascript to get current time in the process of website development, such as displaying the current time in a web page. There is no function to directly get the current time, but only through the date function in javascript. The date function can get the year, month, day, hour, minute, and second separately, and combine them as needed. You can get only the time or date, or they can be both. In addition, the current time can be returned in milliseconds.

 

1. Javascript get current time

var d = new Date();
       var currTime = "Current time: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
       alert(currTime);

 

2. Javascript get current date time

var d = new Date();
       var year = d.getYear()<1900?(1900+d.getYear()):d.getYear();
       var currDateTime = "Current date and time: " + year + "/" + (d.getMonth() + 1 ) + "/" + d.getDate() + "/ " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
       alert(currDateTime);

 

3. Javascript get current time in milliseconds

var timeStamp = (new Date()).valueOf();

Or

var timeStamp1 = new Date().getTime();

Or

var timeStamp2 = Date.now();

alert(timeStamp + "; " + timeStamp1 + "; " + timeStamp2);

 

Complete code(saved as html file to run and test):

<!DOCTYPE html>
<html>
<head>
       <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
        <title>Javascript get current time, with getting it in milliseconds and current date</title>
       <style type="text/css">
              .content{
                            width:500px;
                            overflow:hidden;
               }
       </style>
</head>
<body>
       <div class="content">
                      <script language="JavaScript" type="text/javascript">
                                           var date,year;
                                           var d = new Date();
                                           year = d.getYear() <1900?(1900+d.getYear()):d.getYear();

 

                                    date = "Current time: " + (d.getMonth() + 1 )+ "/" + d.getDate() + "/" + year + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

                                   var timeStamp = (new Date()).valueOf();
                                          document.write(date + "<br />Get current time in milliseconds: " + timeStamp);
                      </script>
         </div>
</body>
</html>