前端面试: 使用js的 Date 对象来将日期和时间拼接成时间戳格式

前端面试: 使用js的 Date 对象来将日期和时间拼接成时间戳格式

编码文章call10242024-12-22 14:43:1234A+A-

问题描述:

js 实现某年月日时间如2023-05-23和某一段时分的时间如12:30进行拼接转化成时间戳格式。

解决方案

1.可以使用 JavaScript 的 Date 对象来将日期和时间拼接成时间戳格式,具体实现如下:

// 定义年月日和时分
const year = 2023;
const month = 4; // 月份从 0 开始计数,所以实际是 5 月
const day = 23;
const hour = 12;
const minute = 30;

// 将年月日和时分拼接成字符串
const dateString = `${year}-${month + 1}-${day} ${hour}:${minute}:00`;

// 将字符串转化为时间戳
const timestamp = new Date(dateString).getTime() / 1000;

console.log(timestamp); // 输出时间戳

注意,JavaScript 中的时间戳是以毫秒为单位的,而 Unix 时间戳是以秒为单位的,因此需要将 JavaScript 的时间戳除以 1000 来得到 Unix 时间戳。

2.使用 dayjs 库来实现相同的功能也非常简单,具体实现如下:

// 引入 dayjs 库
const dayjs = require('dayjs');

// 定义年月日和时分
const year = 2023;
const month = 4; // 月份从 0 开始计数,所以实际是 5 月
const day = 23;
const hour = 12;
const minute = 30;

// 将年月日和时分拼接成字符串,并转化为 dayjs 对象
const datetime = dayjs(`${year}-${month + 1}-${day} ${hour}:${minute}:00`);

// 将 dayjs 对象转化为时间戳
const timestamp = datetime.unix();

console.log(timestamp); // 输出时间戳

在这个例子中,我们首先引入了 dayjs 库,然后将年月日和时分拼接成字符串,并使用 dayjs 函数将其转化为 dayjs 对象。最后,我们使用 unix 方法将 dayjs 对象转化为时间戳。

需要注意的是,在 dayjs 中,时间戳默认是以秒为单位的,因此不需要在转化时间戳时除以 1000。



#挑战30天在头条写日记#

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4