JS to get the current date and time
var date = new Date(); date.getYear(); //获取当前年份(2位) date.getFullYear(); //获取完整的年份(4位,2014) date.getMonth(); //获取当前月份(0-11,0代表1月) date.getDate(); //获取当前日(1-31) date.getDay(); //获取当前星期X(0-6,0代表星期天) date.getTime(); //获取当前时间(从1970.1.1开始的毫秒数) date.getHours(); //获取当前小时数(0-23) date.getMinutes(); //获取当前分钟数(0-59) date.getSeconds(); //获取当前秒数(0-59) date.getMilliseconds(); //获取当前毫秒数(0-999) date.toLocaleDateString(); //获取当前日期 如 2014年6月25日 date.toLocaleTimeString(); //获取当前时间 如 下午4:45:06 date.toLocaleString(); //获取日期与时间 如 2014年6月25日 下午4:45:06
Note: Both getYear() and getFullYear() can get the year, but they are slightly different
getYear() is displayed in the browser as: 114 (taking 2014 as an example). The reason is that getYear returns the value of "current year-1900" (that is, the year base is 1900)
Use JS to get the year: getFullYear()
Refresh regularly
SetInterval is used for scheduled refresh. Please refer to other materials for the specific difference between setTimeout and setInterval.
1. First, the page needs an area to display the time
<div id="showDate"></div>
2. Obtain time
<script type="text/javascript"> $(function(){ setInterval("getTime();",1000); //每隔一秒执行一次 }) //取得系统当前时间 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); //将值赋给div } </script>
Use toLocaleDateString() to directly obtain the year, month and day, no need to obtain the year, month and day separately
ToLocaleTimeString() can directly obtain hours, minutes and seconds, because the format it obtains is not required. So it can be obtained separately.