js formats the date in iso 8601 format to other formats - handles the default golang time type format problem

When the golang time type format is serialized to json by default, it is in the iso 8601 format

for example:

2023-03-09T23:43:43+08:00

A time notation in ISO 8601 format, commonly used to represent worldwide times and dates. The ISO 8601 format uses the hyphen "-" to separate the date and time parts, and the letter "T" to separate the date and time parts, where the "T" is followed by the time part. In this time representation, "2023-03-09" represents the date part, and "23:43:43+08:00" represents the time part and time zone offset. Among them, "+08:00" means an offset of 8 hours relative to UTC time, that is, Beijing time.

You can use the following functions for formatting

function formatDate(dateString, format = 'yyyy-MM-dd HH:mm:ss') {
  const date = new Date(dateString);

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  const formattedDate = format
    .replace(/yyyy/g, year)
    .replace(/MM/g, month)
    .replace(/dd/g, day)
    .replace(/HH/g, hour)
    .replace(/mm/g, minute)
    .replace(/ss/g, second);

  return formattedDate;
}

// 示例用法
console.log(formatDate('2022-03-09 23:43:43')); // 输出:2022-03-09 23:43:43
console.log(formatDate('03/09/2022', 'yyyy年MM月dd日')); // 输出:2022年03月09日
console.log(formatDate('09 Mar 2022 23:43:43 GMT', 'yyyy-MM-dd HH:mm:ss')); // 输出:2022-03-09 23:43:43

Guess you like

Origin blog.csdn.net/taoshihan/article/details/129434743