Date对象和简单的时间格式化函数

194 阅读2分钟

写在最前

当我们在平常开发中难免要对时间对象进项处理,这个时候我们就需要对时间对象化进行处理,面是几种时间格式化的方法,以及常用的一些方法:形如将时间对象转换为YYYY-MM-dd格式等等.

Date对象

  • 当前时间(Date格式)
//中国标准时间对象东八区时间
    console.log(new Date());//Thu Aug 11 2022 18:21:06 GMT+0800 (中国标准时间)
//注意:如果我们直接将此时间进行格式转化,转换为json字符串会出现时间误差问题
  • 当前时间(时间戳格式)
    console.log(new Date().getTime());//1660216937127
  • 当前时间(年、月、日、周几、时、分、秒)
  console.log('年', new Date().getFullYear());
  console.log('月',new Date().getMonth()+1);//月份是从0开始计数,所以我们在获取月份的时候一定记得加1
  console.log('日',new Date().getDate());
  console.log('星期', new Date().getDay());
  console.log('时', new Date().getHours());//12小时制需要判断输出是否大于12即可实现
  console.log('分', new Date().getMinutes());
  console.log('秒', new Date().getSeconds());

image.png

  • 将时间对象转换为时间戳和时间大小比较
      //日期大小比较
      let a = new Date("2022-01-02");
      let b = new Date("2022-02-02");
      if (a > b) {
        console.log("a>b");
      } else {
        console.log("a<b");
      }
      //将时间对象转为时间戳
      console.log(Date.parse(new Date("2022-01-02")));

几个日期格式化的方法以及一些常用日期的功能

形如yyyy-MM-dd格式等等

      //时间格式函数 0补全函数(按需)
      function padLeftZero(str) {
        return ("00" + str).substr(str.length);
      }
      //时间格式化  date为日期对象 fmt为目标日期格式
      //可以有的格式: yyyy-MM-dd hh:mm:ss 或者 yyyyMMdd 或者 yyyy年MM月dd日 等等
      formatDate = (date, fmt) => {
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        }
        const o = {
          "M+": date.getMonth() + 1,
          "d+": date.getDate(),
          "h+": date.getHours(),
          "m+": date.getMinutes(),
          "s+": date.getSeconds(),
        };
        for (const k in o) {
          if (new RegExp(`(${k})`).test(fmt)) {
            const str = o[k] + "";
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length === 1 ? str : padLeftZero(str)
            );
          }
        }
        return fmt;
      };
      console.log(formatDate(new Date(), "yyyy-MM-dd"));

给定日期和天数计算目标日期

      //计算date后days天是几号
      //date格式可以是Date对象、'yyyy-MM-dd'、'yyyy-MM-dd hh:mm:ss'
      //days是Number类型
      daysAfterDate = (date, days) => {
        let now = Date.parse(date);
        let after = now + Number(days) * (1000 * 60 * 60 * 24);
        return new Date(after);
      };
      console.log(daysAfterDate('2022-08-05 00:00:00',5));//得到的是日期对象