JavaScript filter time processing function

1. Create a new js file, the code is as follows:

function filterTime(inputDate, filter) {
  const date = new Date(inputDate); // 将输入日期字符串转换为日期对象
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  const filters = {
    'yyyy': year,
    'MM': ('0' + month).slice(-2),
    'dd': ('0' + day).slice(-2),
    'HH': ('0' + hours).slice(-2),
    'mm': ('0' + minutes).slice(-2),
    'ss': ('0' + seconds).slice(-2)
  };

  let result = filter;
  for (let key in filters) {
    result = result.replace(key, filters[key]); // 使用正则表达式替换模板中的时间格式
  }

  return result;
}

2. Introduce the newly created js page to the page you use

const inputDate = '2023-04-01T12:34:56.789Z';
const filter = 'yyyy年MM月dd日 HH:mm:ss';
const result = filterTime(inputDate, filter);
console.log(result); // 输出: "2023年04月01日 12:34:56"

In the above example, inputDate it is a date string in ISO format, filterwhich is a template string in date format. The function will replace the corresponding part of the input date according to the format in the template string, and return the formatted date string .

Guess you like

Origin blog.csdn.net/Guanchong333/article/details/129900666