JS get current date and time
Var date = new Date (); date. getYear (); // obtain the current year (2 digits) date. getFullYear (); // obtain the complete year (4 bits, 2014) date. getMonth (); // obtain the current month (0-11, 0 represents January) date. getDate (); // get the current day (1-31) date. getDay (); // obtain the date of the current week X (0-6, 0 represents Sunday. getTime (); // get the current time (milliseconds starting from 1970.1.1) date. getHours (); // obtain the current hour (0-23) date. getMinutes (); // get the current number of minutes (0-59) date. getSeconds (); // obtain the current number of seconds (0-59) date. getMilliseconds (); // get the current number of milliseconds (0-999) date. toLocaleDateString (); // obtain the current date, for example, January 1, June 25, 2014 date. toLocaleTimeString (); // obtain the current time, such as 4:45:06 date. toLocaleString (); // obtain the date and time, such as June 25, 2014 4:45:06
Note: Both getYear () and getFullYear () can obtain the year, but the two are slightly different.
GetYear () is displayed in the browser as 114 (for example, January 1, 2014), because getYear returns the value of "current year-1900" (that is, the year base is 1900)
Use JavaScript to retrieve the year: getFullYear ()
Timed refresh
SetInterval is used for timed refresh. For details about the difference between setTimeout and setInterval, refer to other materials.
1. First, the page requires a region for displaying the time
<div id="showDate"></div>
2. Obtain the time
<Script type = "text/javascript" >$ (function () {setInterval ("getTime ();", 1000); // execute once every second }) // obtain 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 directly obtain the year, month, and day. You do not need to obtain the year, month, and day separately.
ToLocaleTimeString () can be used to directly obtain the hour, minute, and second, because the format it gets is not required. Therefore, it can be obtained separately.