JavaScript动态获取时间小组件

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日的毫秒数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值