JS内置对象Date() (学习整理)

 let now = new Date()
        console.log(now);//打印当前日期
        console.log(now.getFullYear());//打印年
        console.log(now.getMonth() + 1);//打印月(月份要+1)
        console.log(now.getDate());//打印日
        console.log(now.getHours());//打印小时
        console.log(now.getMinutes());//打印分钟
        console.log(now.getSeconds());//打印秒钟

打印例如“2020-09-02 15:23:36”的日期(此例子打印的是当前网络时间)

let ymd = ([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-'));
let hms = ([now.getHours(), now.getMinutes(), now.getSeconds()].join(':'));
let all = [ymd, hms].join('  ')
   console.log(ymd);
   console.log(hms);
   console.log(all);

打印今天是星期几

console.log(now.getDay()); //获取星期0-6
let str = '星期' + '日一二三四五六' [now.getDay()] //输出今天是星期几
console.log(str);

微信朋友圈动态发布时间demo

        let d3 = new Date()
        let d4 = new Date('2020-08-31 16:24:22')
        let ymd = [d4.getFullYear(), d4.getMonth() + 1, d4.getDate()].join('-');
        let hms = [d4.getHours(), d4.getMinutes(), d4.getSeconds()].join(':');
        let sec = (d3 - d4) / 1000 //毫秒变成秒
        if (sec < 60) {
            console.log('刚刚');
        } else if (sec < 60 * 60) {
            console.log(Math.floor(sec / 60) + '分钟前');
        } else if (sec < 60 * 60 * 24) {
            console.log(Math.floor(sec / 60 / 60) + '小时前');
        } else {
            console.log(`${ymd} ${hms}`);
        }

定时器

//定时器
setInterval(function () {
  let ymd = ([now.getFullYear(), now.getMonth() + 1,now.getDate()].join('-'));
  let hms = ([now.getHours(), now.getMinutes(), now.getSeconds()].join(':'));
  let all = [ymd, hms].join('  ')
  console.log(all);
}, 1000)

倒计时demo

// 倒计时
        let time = new Date()
        let six = new Date('2020-08-31 18:00:00')
        let sec = (six - time) / 1000
        let hour = (Math.floor(sec / 3600));
        let minute = (Math.floor(sec % 3600 / 60));
        let second = (Math.floor(sec % 3600 % 60));
        hour = hour < 10 ? ('0' + hour) : hour
        minute = minute < 10 ? ('0' + minute) : minute
        second = second < 10 ? ('0' + second) : second
        console.log([hour, minute, second].join(':'));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值