JS时间对象new Date()的常用方法和格式化时间日期

new Date(), //Sat May 22 2021 10:38:06 GMT+0800 (中国标准时间)
//返回时间戳
+new Date(); //1621651748005
Date.now();//1621651748005
new Date().getTime()//1621651748005

new Date().toJSON(), //2021-05-22T02:38:06.765Z
new Date().toISOString(), //2021-05-22T02:38:06.765Z
new Date().toDateString(), //Sat May 22 2021

new Date().toLocaleString(), //2021/5/22上午10:38:06
new Date().toLocaleDateString(), //2021/5/22
new Date().toLocaleTimeString(), //"上午10:40:24"
//加参数的
new Date(1621541748005).toLocaleString()//2021/5/21上午4:15:48

getDate()获取当前日期对象是几日(1-31)
getDay()获取当前日期对象是周几(返回0-6.0表示周日.1表示周一)
getMonth()获取当前月份(0-11.0表示一月.11表示12)
geFullYear()获取当前年份
geHours()获取小时(0-23)
geMinutes()获取分钟(0-59)
geSeconds()获取秒数(0-59)
geMilliseconds()获取毫秒数

格式化日期

 function dateFormat(date, fmt = "yyyy年MM月dd日") {
      if (date == null) return null;
      if (typeof date === "string") {
        date = date.slice(0, 19).replace("T", " ").replace(/-/g, "/");
        date = new Date(date);
      } else if (typeof date === "number") {
        date = new Date(date);
      }
      var o = {
        "M+": date.getMonth() + 1,
        "[Dd]+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
        "q+": Math.floor((date.getMonth() + 3) / 3),
        S: date.getMilliseconds(),
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
      }
      return fmt;
    }
    console.log(dateFormat("2022-11-02T02:51:56.373Z", "yyyy年MM月DD日 hh:mm:ss")); //2022年11月02日 02:51:56
    console.log(dateFormat(new Date())); //2022年11月02日
    console.log(dateFormat(1667358481422)); //2022年11月02日

常用格式为:yyyy-MM-dd HH:mm:ss
在这里插入图片描述

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C+ 安口木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值