枯燥的js 时间戳

转换时间戳

const date = new Date("1997-7-12 08:22:12");
       console.log(date);
       console.log(date*1);
       console.log(Number(date));
       console.log(date.valueOf());
       console.log(date.getTime());

在这里插入图片描述
时间戳转换为时间

const date = new Date();
       const timestamp = date.valueOf();
       console.log(timestamp);
       console.log(new Date(timestamp));

在这里插入图片描述

获取时间函数

 const date = new Date();
       function dateFormat(date,format="YYYY-MM-DD HH:mm:ss"){
           console.log(format);
            const config ={
                YYYY:date.getFullYear(),
                MM:date.getMonth(),
                DD:date.getDate(),
                HH:date.getHours(),
                mm:date.getMinutes(),
                ss:date.getSeconds()
         }
         for(const key in config){
            format = format.replace(key,config[key]);
            console.log(key);
         }
         console.log(format);
         return format;
       }
       console.log(dateFormat(date,"YYYY年MM月DD日"))

在这里插入图片描述
date首先获取当前时间,我们传入我需要的格式。
传入的format就变成我们传入的格式了。
再利用for in循环遍历config,config对象用于取出时间的年月日时分秒。
再利用replace函数,替换format里面的YYYY MM等。
年月日时分秒不能是同一字母构成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值