新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

js格式化时间的有哪些方法,js格式化时间戳

发布时间:2023-12-15 00:00:29

js格式化时间的有哪些方法

在JavaScript中,有几种格式化时间的方法,以下是一些经常使用的方法:

  1. 使用toLocaleString()方法:
const date = new Date();
const formattedDate = date.toLocaleString();
console.log(formattedDate); // Output: "5/3/2022, 9:45:30 PM" (based on the user's locale)
  1. 使用toISOString()方法:
const date = new Date();
const formattedDate = date.toISOString();
console.log(formattedDate); // Output: "2022-05-03T21:45:30.000Z"
  1. 使用第三方库,如Moment.js:
const date = new Date();
const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate); // Output: "2022-05-03 21:45:30"
  1. 手动格式化日期:
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate); // Output: "2022-05-03 21:45:30"

这些方法可以根据自己的需求选择使用,每种方法都有区分的输出格式。