Get the current time and convert it to the desired format

Convert to YYYY-MM-DD format

function getCurrentDate() {
  var today = new Date();
  var year = today.getFullYear();
  var month = today.getMonth() + 1; // 月份从0开始,需要加1
  var day = today.getDate();
  return year + '-' + (month < 10 ? ('0' + month) : month) + '-' +  (day < 10 ? ('0' + day) : day);
};
const time =  this.getCurrentDate()
console.log(time);

Convert to YYYY-MM-DD HH:MM:SS / YYYY.MM.DD HH:MM:SS format

  getCurrentTime() {
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth() + 1; // 月份从0开始,所以需要加1
  const day = currentDate.getDate();
  const hours = currentDate.getHours();
  const minutes = currentDate.getMinutes();
  const seconds = currentDate.getSeconds();

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  //return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`;
},

const time =  this.getCurrentTime()
console.log(time);

Convert to YYYY year MM month DD day/YYYY.MM.DD format

function getCurrentDateFormatted() {
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始,需要加1,并且保证两位数
  const day = currentDate.getDate().toString().padStart(2, '0'); // 保证日期为两位数
    
  return `${year}年${month}月${day}日`;
  //YYYY.MM.DD格式 return `${year}.${month}.${day}`;
}

const formattedDate = getCurrentDateFormatted();
console.log(`当前日期:${formattedDate}`);

おすすめ

転載: blog.csdn.net/weixin_53818172/article/details/132716472