function formatChinaTime(timestamp, format) {
  const date = new Date(timestamp);
  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 padZero = (num) => (num < 10 ? `0${num}` : num); // helper function to add leading zero if needed
  const formattedDate = format
    .replace('yyyy', year)
    .replace('MM', padZero(month))
    .replace('dd', padZero(day))
    .replace('HH', padZero(hour))
    .replace('mm', padZero(minute))
    .replace('ss', padZero(second));
  return formattedDate;
}

带注释版

// 定义一个函数,用于将时间戳转换为指定格式的时间
function formatChinaTime(timestamp, format) {
  const date = new Date(timestamp); // 创建一个 Date 对象,传入时间戳
  const year = date.getFullYear(); // 获取年份
  const month = date.getMonth() + 1; // 获取月份,需要加 1
  const day = date.getDate(); // 获取日期
  const hour = date.getHours(); // 获取小时
  const minute = date.getMinutes(); // 获取分钟
  const second = date.getSeconds(); // 获取秒数
  const padZero = (num) => (num < 10 ? `0${num}` : num); // 定义一个函数,用于在数字前面补 0
  const formattedDate = format
    .replace('yyyy', year) // 将格式字符串中的 yyyy 替换为年份
    .replace('MM', padZero(month)) // 将格式字符串中的 MM 替换为月份,并在前面补 0
    .replace('dd', padZero(day)) // 将格式字符串中的 dd 替换为日期,并在前面补 0
    .replace('HH', padZero(hour)) // 将格式字符串中的 HH 替换为小时,并在前面补 0
    .replace('mm', padZero(minute)) // 将格式字符串中的 mm 替换为分钟,并在前面补 0
    .replace('ss', padZero(second)); // 将格式字符串中的 ss 替换为秒数,并在前面补 0
  return formattedDate; // 返回格式化后的时间字符串
}
文章目录