function formatDate(date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  const formattedDate = `${year}-${addLeadingZero(month)}-${addLeadingZero(day)}`;
  const formattedTime = `${addLeadingZero(hour)}:${addLeadingZero(minute)}:${addLeadingZero(second)}`;
  return `${formattedDate} ${formattedTime}`;
}

function addLeadingZero(number) {
  return number < 10 ? `0${number}` : number;
}

const date = new Date();
console.log(formatDate(date)); // 输出格式:2021-01-01 00:00:00

以上代码实现了将一个 JavaScript Date 对象格式化为 'YYYY-MM-DD HH:mm:ss' 的字符串输出。'addLeadingZero' 函数用于给小于 10 的数字前面加 0,如将 1 转换成 01。通过模板字符串和字符串拼接得到最终的格式化字符串。

JavaScript 时间格式化:将 Date 对象转换为 'YYYY-MM-DD HH:mm:ss' 字符串

原文地址: https://www.cveoy.top/t/topic/l5j9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录