JavaScript 中 new Date() 生成的日期格式转换为 ‘yyyy-MM-dd HH:mm:ss’ 格式的字符串

1、使用 Date 对象自带的方法
可以使用 Date 对象自带的方法来获取日期字符串的各个部分,然后将它们拼接成目标格式的字符串:

function formatDate(date) {
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  const hours = ('0' + date.getHours()).slice(-2);
  const minutes = ('0' + date.getMinutes()).slice(-2);
  const seconds = ('0' + date.getSeconds()).slice(-2);
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const date = new Date();
const formattedDate = formatDate(date);
console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串

2、使用第三方库
也可以使用第三方库来格式化日期字符串,如 moment.js:

const moment = require('moment');

const date = new Date();
const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串

或者使用 ES6 的模板字符串和 Date 对象自带的方法:

const date = new Date();
const formattedDate = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)} ${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}:${('0' + date.getSeconds()).slice(-2)}`;
console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐