function nowtime() {
let time = new Date();
let getyear = time.getFullYear();
let getmonth = time.getMonth() + 1;
let getday = time.getDate();
let gethours = time.getHours();
let getminutes = time.getMinutes();
let getseconds = time.getSeconds();
let timeshowarea = document.querySelector(".nowTime");
getmonth < 10 ? (getmonth = "0" + getmonth) : getmonth;
getday < 10 ? (getday = "0" + getday) : getday;
gethours < 10 ? (gethours = "0" + gethours) : gethours;
getminutes < 10 ? (getminutes = "0" + getminutes) : getminutes;
getseconds < 10 ? (getseconds = "0" + getseconds) : getseconds;
timeshowarea.innerHTML = `${getyear}年${getmonth}月${getday}日${gethours}:${getminutes}:${getseconds}`;
}
setInterval(nowtime, 1000);
实现原理
日期对象var mydate = new Date()
获取
- mydate.toLocaleDateString()
根据本地时间把 Date 对象的日期部分转换为字符串,并返回结果 - mydate.toLocaleTimeString()
根据本地时间把 Date 对象的时间部分转换为字符串,并返回结果 - mydate.toLocaleString()
根据本地时间把 Date 对象的日期与时间部分转换为字符串,并返回结果 - mydate.getFullYear() 获取年份
- mydate.getMonth() 获取月份 0-11 0–>1月份 1–>2月份
- mydate.getDate() 获取日期
- mydate.getHours() 获取小时
- mydate.getMinutes() 获取分钟
- mydate.getSeconds() 获取秒
- mydate.getMilliseconds() 获取毫秒
- mydate.getDay() 获取星期 0-60–>星期日 1–>星期一
- mydate.getTime() 获取距离1970年1月1日的毫秒数
设置
- var mydate = new Date(“yyyy/mm/dd hh:mm:ss”)
- mydate.setFullYear(yyyy) 设置年份
- mydate.setMonth(mm) 设置月份 0-11 0–>1月份 1–>2月份
- mydate.setDate(dd) 设置日期
- mydate.setHours(hh) 设置小时
- mydate.setMinutes(mm) 设置分钟
- mydate.setSeconds(ss) 设置秒
- mydate.setMilliseconds(ms) 设置毫秒
- mydate.setTime(tt) 设置距离1970年1月1日的毫秒数