JS格式化输出当前时间戳:getDateTimeString() \ formatDateTime()

function getDateTimeString() {
  const now = new Date()
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();
  const hours = now.getHours();
  const minutes = now.getMinutes();
  const seconds = now.getSeconds();
  return [year, month, day, hours, minutes, seconds].map((num) => {
    if (num < 10) {
      return '0' + num;
    }
    return num;
  }).join('')
}

  

function getDateTimeString2() {
  const d = new Date();
  const n = d.toISOString();
  return n.replace(/[^0-9]/gm, '');
}

 

 

function formatDateTime(now) {
  const fix = (num) => {
    return num < 10 ? '0' + num : num
  }
  const year = now.getFullYear();
  const month = fix(now.getMonth() + 1);
  const day = fix(now.getDate());
  const hours = fix(now.getHours());
  const minutes = fix(now.getMinutes());
  const seconds = fix(now.getSeconds());
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

  

posted on 2024-01-05 11:06  袜子破了  阅读(53)  评论(0编辑  收藏  举报