Cómo convertir la marca de tiempo a la fecha, se muestran diferentes tipos de tiempo

Convertir una marca de tiempo en una fecha en realidad no es difícil. Sin más preámbulos, sirvamos la comida directamente.

//时间戳转化日期
  formatDate(str){
    //Date.now()        //时间戳
    str = str*1000        //时间戳化成毫秒单位
    let date = new Date(str);        //获取系统时间
    let year = date.getFullYear();
    let month= date.getMonth() + 1;
    month= month< 10 ? ('0' + month) : month;
    let day = date.getDate();
    day = day < 10 ? ('0' + day ) : day ;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s;
    //let w = date.getDay();        //获取星期几

    
    return year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s;
  },

Encapsule la marca de tiempo en el tiempo y se podrá usar la llamada.

Date() tiene 7 formularios de parámetros

  1. nueva fecha ("mes dd, aaaa hh: mm: ss");
  2. nueva fecha ("mes dd, aaaa");
  3. nueva Fecha("aaaa/MM/dd hh:mm:ss");
  4. nueva Fecha("aaaa/MM/dd");
  5. nueva fecha (aaaa, mes, dd, hh, mm, ss);
  6. nueva fecha (aaaa, mes, dd);
  7. nueva fecha (ms);

 getTime() 、Date.parse() 、date.valueOf()

getTime() , Date.parse() , date.valueOf()    //Obtenga la marca de tiempo y convierta la fecha en un formato determinado en una marca de tiempo

(Desde el 1 de enero de 1970 hasta la actualidad) El primer y segundo tipo: tendrán una precisión de milisegundos. El tercer tipo: solo con precisión de segundos, los milisegundos serán reemplazados por 0

Fecha de formato de parámetro:

  1. Fecha.parse("aaaa,mes,dd hh:mm:ss")
  2. Fecha.parse("aaaa/MM/dd hh:mm:ss")
  3. Fecha.parse("aaaa/MM/dd")
  4. Fecha.parse("aaaa,mes,dd")
  5. Fecha.parse("mes dd, aaaa")

 

También se muestran diferentes tipos de tiempo :

new Date().toLocaleDateString()
'2021/12/22'

new Date().toLocaleString()
'2021/12/22 上午9:36:34'

new Date().toLocaleTimeString()
'上午9:36:48'

new Date().toISOString()
'2021-12-22T01:35:48.757Z'

new Date().toJSON()
'2021-12-22T01:34:47.853Z'

new Date().toGMTString()
'Wed, 22 Dec 2021 01:35:29 GMT'

new Date().toDateString()
'Wed Dec 22 2021'

new Date().toUTCString() 
'Wed, 22 Dec 2021 01:37:26 GMT'

new Date().toString()
'Wed Dec 22 2021 09:44:24 GMT+0800 (中国标准时间)'

new Date().toTimeString()
'09:44:29 GMT+0800 (中国标准时间)'

De hecho, qué tipo de fecha desea, es mejor encapsular un método para facilitar el uso del proyecto.

La marca de tiempo se convierte en una fecha y hora y se muestra el tipo de fecha.

Si hay algún error en la descripción, por favor corrígeme!

Supongo que te gusta

Origin blog.csdn.net/m0_70015558/article/details/124644124
Recomendado
Clasificación