JavaScript获取格式化当前时间

在 JavaScript 中,可以使用 Date 对象获取当前时间并将其格式化为 yyyymmddhhmmss 的形式。

function getCurrentTimeFormatted() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ('0' + (now.getMonth() + 1)).slice(-2);
  const day = ('0' + now.getDate()).slice(-2);
  const hours = ('0' + now.getHours()).slice(-2);
  const minutes = ('0' + now.getMinutes()).slice(-2);
  const seconds = ('0' + now.getSeconds()).slice(-2);

  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

这段代码首先创建一个 Date 对象来表示当前时间。然后,它使用 getFullYeargetMonthgetDategetHoursgetMinutesgetSeconds 方法提取年份、月份、日期、小时、分钟和秒。

为了确保月份、日期、小时、分钟和秒都以两位数字表示,代码使用了字符串切片。例如,('0' + (now.getMonth() + 1)).slice(-2) 会将月份转换为两位数字的字符串,如果月份小于 10,则会在前面添加一个零。

最后,代码将所有部分连接成一个字符串,并以 yyyymmddhhmmss 格式返回。

txt 文件大小:456B