Convert the obtained timestamp into normal format in js

 

In the development process, you will most likely encounter a request server. The time data returned by the server is presented in the form of a timestamp. At this time, we need to convert the timestamp format to the normal time format in our lives.

1. Stitch by yourself in the form of Date object method.

① First, convert the timestamp into a Date object. The timestamp is usually in seconds, so when it is passed to the Date, it must be multiplied by 1000. If the returned timestamp is in milliseconds, there is no need to multiply it by 1000.

const date = new Date(时间戳*1000)

② Get the Date object and convert this object into a corresponding string.

The Date object has corresponding methods: the following are the more commonly used ones.

//获取当前年份的后2位
date.getYear(); 

//获取4位数的完整年份
date.getFullYear(); 

//获取当前月份,从0-11月,0代表1月,依次下去,所以一般+1才是正常月份数字
date.getMonth();
 
//获取当前日,从1-31日,正常获取
date.getDate(); 

//获取当前星期几,从0-6,0代表星期天,其余正常
date.getDay(); 

//获取当前小时,从0-23点
date.getHours(); 

//获取当前分钟,从0-59分钟
date.getMinutes(); 

//获取当前秒,从0-59秒
date.getSeconds(); 

③Choose from the above methods, and then splicing.

2. Encapsulate a formatDate (time stamp, "time output format") method by yourself.

Time output format: "yyyy-MM-dd hh:mm:ss"

yyyy: represents the complete 4-digit year. If written as yy, then the formatted number is a two-digit year.

MM: In order to distinguish it from the minute, I use an uppercase M. Generally speaking, the two-digit month is formatted.

dd: the number of dates.

hh: time points, HH represents the 24-hour system, hh represents the 12-hour system.

mm: The number of minutes.

ss: The number of seconds.

The following code source network, the source is not clear, please read and use, thank the creator!

Used in components: (remember to import) 

// 假设传入的value是秒级时间戳
showDate: function (value) {
      let date = new Date(value * 1000);
      return formatDate(date, "yyyy-MM-dd hh:mm");
    }

Encapsulate a method in utils.js: 

function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}

// 时间格式化
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };

  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
    }
  }

  return fmt;
}

The above can format the timestamp returned by the server.

Guess you like

Origin blog.csdn.net/michaelxuzhi___/article/details/106166188