JS gets the current date time and periodically refreshes the example

  • 2020-03-30 03:25:41
  • OfStack

JS gets the current date and time


var date = new Date(); 
date.getYear(); //Get current year (2 bits)
date.getFullYear(); //Get the full year (4-bit,2014)
date.getMonth(); //Get the current month (0-11,0 for January)
date.getDate(); //Get current day (1-31)
date.getDay(); //Get the current week X(0-6,0 for Sunday)
date.getTime(); //Gets the current time (number of milliseconds since 1970.1.1)
date.getHours(); //Gets the current number of hours (0-23)
date.getMinutes(); //Gets the current number of minutes (0-59)
date.getSeconds(); //Gets the current number of seconds (0-59)
date.getMilliseconds(); //Gets the current number of milliseconds (0-999)
date.toLocaleDateString(); //Gets the current date such as June 25, 2014
date.toLocaleTimeString(); //Gets the current time such as 4:45:06 p.m
date.toLocaleString(); // Gets the date and time   Such as  2014 years 6 month 25 day   In the afternoon 4:45:06

Note: getYear() and getFullYear() both get the year, but there is a slight difference

GetYear () displays 114 in the browser (take 2014 as an example) because getYear returns the value of "current year-1900" (that is, the year base is 1900)

GetFullYear () getFullYear() getFullYear() getFullYear()

Time to refresh

SetInterval is used for regular refresh, and the difference between specific setTimeout and setInterval is referred to other information.

1. First, the page needs an area for display time


<div id="showDate"></div>

2. Get time


<script type="text/javascript"> 
$(function(){ 
setInterval("getTime();",1000); //Execute every second
}) 
//Gets the current system time
function getTime(){ 
var myDate = new Date(); 
var date = myDate.toLocaleDateString(); 
var hours = myDate.getHours(); 
var minutes = myDate.getMinutes(); 
var seconds = myDate.getSeconds(); 
$("#showDate").html(date+" "+hours+":"+minutes+":"+seconds); //Assign the value to div
} 
</script>

Use toLocaleDateString() to get the year, month, and day directly instead of getting the year, month, and day separately

ToLocaleTimeString (), on the other hand, gets the minutes and seconds directly because the format it gets is not required. So it can be obtained separately.


Related articles: