Formattedly convert a timestamp to a date object

DateTimestamps can be formatted using the object in JavaScript . The specific implementation can be carried out according to the following steps:

  1. Convert a timestamp to a date object. In JavaScript, you can use new Date(timestamp)the method to convert a timestamp to a date object, and timestamp is a timestamp.

  2. getYear()Use the , getMonth(), getDate(), getHours(), getMinutes(), and other methods of the date object getSeconds()to obtain time units such as year, month, day, hour, minute, and second.

  3. The time format required for splicing.

The following is an example code for converting a timestamp to a date in a specified format:

function formatDate(timestamp, format) {
    
    
  // 将时间戳转换为日期对象
  const date = new Date(timestamp);
  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();

  // 替换需要的时间格式
  format = format.replace('yyyy', year);
  format = format.replace('MM', month < 10 ? '0' + month : month);
  format = format.replace('dd', day < 10 ? '0' + day : day);
  format = format.replace('HH', hours < 10 ? '0' + hours : hours);
  format = format.replace('mm', minutes < 10 ? '0' + minutes : minutes);
  format = format.replace('ss', seconds < 10 ? '0' + seconds : seconds);

  return format;
}

// 示例代码
console.log(formatDate(1619097074830, 'yyyy-MM-dd HH:mm:ss')); // 2021-04-22 18:57:54

In the above code, we defined a formatDate function that receives two parameters: timestamp and format string. After using new Date(timestamp)the method to convert the timestamp into a date object, use various methods of the date object to obtain time units such as year, month, day, hour, minute, second, etc., and finally use the replacement method of the string to replace the placeholder in the format string character is replaced with the actual time value to generate a date string in the specified format.

In this way, a simple timestamp formatting function is implemented, and the format string can be modified as needed to achieve more time format conversions.

Guess you like

Origin blog.csdn.net/z2000ky/article/details/130623858