JS get current date and time
var date = new Date(); date.getYear(); //Get the current year (2 digits) date.getFullYear(); //Get the full year (4 digits, 2014) date.getMonth(); //Get the current month (0-11, 0 represents January) date.getDate(); //Get the current day (1-31) date.getDay(); //Get the current week X (0-6, 0 represents Sunday) date.getTime(); //Get the current time (milliseconds starting from 1970.1.1) date.getHours(); //Get the current number of hours (0-23) date.getMinutes(); //Get the current number of minutes (0-59) date.getSeconds(); //Get the current number of seconds (0-59) date.getMilliseconds(); //Get the current number of milliseconds (0-999) date.toLocaleDateString(); //Get the current date such as June 25, 2014 date.toLocaleTimeString(); //Get the current time as follows 4:45:06 pm date.toLocaleString(); //Get the date and time as June 25, 2014 at 4:45:06 pm date.toLocaleString(); //Get the date and time as June 25, 2014 at 4:45:06 pm
Note: getYear() and getFullYear() can both get the year, but there is a slight difference between the two.
getYear() is displayed in the browser as: 114 (taking 2014 as an example), because getYear returns the value of "current year-1900" (that is, the year base is 1900)
Use JS to get years using: getFullYear()
Timely refresh
For timed refresh, use setInterval. For specific differences between setTimeout and setInterval, refer to other information.
1. First, the page needs an area to display the time
<div id="showDate"></div>
2. Get time
<script type="text/javascript"> $(function(){ setInterval("getTime();",1000); //Execute every second}) //Get the current time of the system 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 directly obtain the year, month and day, and there is no need to obtain the year, month and day separately.
and toLocaleTimeString() can directly obtain time, minute and second, because the format it obtains is not required. So it can be obtained separately.