【JS】 日期函数Date的基本使用

获取当前时间

const date1 = new Date();
console.log(date1);
console.log(typeof date1); // object

const date2 = Date();
console.log(date2);
console.log(typeof date2); // string

可以看到通过new构造函数返回的是一个对象,而直接调用全局的Date函数返回的是字符串类型。

控制台打印结果:

另外它们各自返回值乘以1的结果也不同。

console.log(date1 * 1); // 获取13位的时间戳
console.log(date2 * 1); // NaN

计算脚本运行时间

利用Date.now()可以获取当前时间戳(指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数)。

const start = Date.now();
for (let index = 0; index < 2000000000; index++) {}
const end = Date.now();
console.log(end - start + "毫秒");
console.log((end - start) / 1000 + "秒");

这里还有一种新颖的计算方式:

console.time("for");
for (let index = 0; index < 2000000000; index++) {}
console.timeEnd("for");

参考官方文档console.time的用法

不同时间格式转换

// 诸如 年-月-日 时:分:秒 形式传入(或2023/01/01)
const d1 = new Date("2023-01-01 12:12:12");
console.log(d1);
console.log(d1.getMonth()); // 0,月份从0~11排序

//  多个字符传入
const d2 = new Date(2023, 1, 2, 11, 12, 13);
console.log(d2);

//  数组传入
const param = [2023, 1, 3, 10, 9, 8];
const d3 = new Date(...param);
console.log(d3);

获取时间戳

这里的时间为中国标准时间(China Standard Time)。

const date = new Date("2023-01-01 12:12:12");
console.log(date * 1);
console.log(date.valueOf());
console.log(Number(date));
console.log(date.getTime());

以上四种方式都能获取都对应时间的时间戳,打印结果是1672546332000。

反之,将时间戳再转换回时间,可以这样做:

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

封装日期格式化函数

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

console.log(dateFormat(new Date(), "YYYY年MM月DD日 HH:mm:ss"));

秉承不要重复造轮子的理念,建议使用一些优秀的日期处理类库,例如Moment.js、Day.js等。

猜你喜欢

转载自blog.csdn.net/weixin_45719444/article/details/128546236