js转换时间戳为正常时间

在这里插入图片描述

文章目录


使用时间戳 1689302591000为案例,可以将其转换为可读的日期和时间格式。在 JavaScript 中,可以使用 Date 对象来进行时间戳的转换和格式化。

以下是将时间戳转换为日期和时间的示例代码:

const timestamp = 1689302591000;
const date = new Date(timestamp);

const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();

const formattedDate = `${
      
      year}-${
      
      month < 10 ? '0' + month : month}-${
      
      day < 10 ? '0' + day : day}`;
const formattedTime = `${
      
      hours < 10 ? '0' + hours : hours}:${
      
      minutes < 10 ? '0' + minutes : minutes}:${
      
      seconds < 10 ? '0' + seconds : seconds}`;

console.log(`日期:${
      
      formattedDate}`);
console.log(`时间:${
      
      formattedTime}`);

以上代码将输出转换后的日期和时间:

日期:2023-03-13
时间:15:36:31

根据提供的时间戳,转换后的日期为 2023 年 3 月 13 日,时间为 15:36:31。请注意,转换结果可能会因为时区等因素而有所差异。

猜你喜欢

转载自blog.csdn.net/weixin_48998573/article/details/131720138
今日推荐