JS get current date and time
var date = new Date(); (); //Get the current year (2 digits)(); //Get the full year (4 digits, 2014)(); //Get the current month (0-11, 0 represents January)(); //Get the current day (1-31)(); //Get the current week X (0-6, 0 represents Sunday)(); //Get the current time (the number of milliseconds starting from 1970.1.1)(); //Get the current number of hours (0-23)(); //Get the current number of minutes (0-59)(); //Get the current number of seconds (0-59)(); //Get the current number of milliseconds (0-999)(); //Get the current date like June 25, 2014(); //Get the current time as 4:45:06 pm(); //Get date and time like 2014Year6moon25day afternoon4:45:06
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()
getMonth() needs to add 1, as shown in the following function
// Get the current date and timefunction getDatetime() { var now = new Date(); var year = (); var month = () + 1; var day = (); var hh = (); var mm = (); var ss = (); var clock = year + "-"; if (month < 10) clock += "0"; clock += month + "-"; if (day < 10) clock += "0"; clock += day + " "; if (hh < 10) clock += "0"; clock += hh + ":"; if (mm < 10) clock += '0'; clock += mm + ":"; if (ss < 10) clock += '0'; clock += ss; return clock; } // Get the current date and timefunction timestampToTime(timestamp) { var date = new Date(timestamp); var Y = () + '-'; var M = (() + 1 < 10 ? '0' + (() + 1) : () + 1) + '-'; var D = () < 10 ? '0' + () : () + ' '; var hh = () < 10 ? '0' + () : () + ':'; var mm = () < 10 ? '0' + () : () + ':'; var ss = () < 10 ? '0' + () : () ; return Y + M + D + hh + mm + ss; }
Timely refresh
For timed refresh, use setInterval. For specific differences between setTimeout and setInterval, refer to other materials.
1. First, the page needs an area to display the time
<div ></div>
2. Get time
<script type="text/javascript"> $(function(){ setInterval("getTime();",1000); //Execute every second}) //Get the current time of the systemfunction getTime(){ var myDate = new Date(); var date = (); var hours = (); var minutes = (); var seconds = (); $("#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.