📌  相关文章
📜  javascript date now format yyyy-mm-dd hh24 mi ss - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:37.297000             🧑  作者: Mango

JavaScript Date Now Format yyyy-mm-dd hh24 mi ss

在 JavaScript 中,可以使用 Date 对象来处理日期和时间,其中 now() 方法返回当前时间的毫秒数。本文将介绍如何将当前时间格式化为 yyyy-mm-dd hh24:mi:ss 的字符串。

const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
const formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
console.log(formattedTime);

这里,我们首先创建一个 Date 对象来获取当前时间,然后取出年月日时分秒,并使用 padStart() 方法将它们转换为固定长度的字符串。最后,将它们按照需要的格式拼接起来即可。

输出结果

2022-08-01 18:51:00

这样,我们就成功将当前时间格式化为指定的字符串格式。

自定义函数

在实际开发中,我们可能需要多次使用这种时间格式化功能,可以将上述代码封装为一个函数,以便于复用。

function formatDateNow() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hour = String(now.getHours()).padStart(2, "0");
  const minute = String(now.getMinutes()).padStart(2, "0");
  const second = String(now.getSeconds()).padStart(2, "0");
  const formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  return formattedTime;
}

console.log(formatDateNow());

这样,我们就可以通过调用 formatDateNow() 函数来获取当前时间的格式化字符串了。

结论

通过上述方法,我们可以将 JavaScript 中的当前时间格式化为各种指定的字符串格式,并通过封装为函数实现复用,方便开发人员使用。