Método de formato y conversión de tiempo js

Recientemente, cuando practico o escribo proyectos, a menudo me encuentro con el problema de la conversión del formato de tiempo.Hoy lo resumiré.

1. Convierta la fecha al formato especificado ( yyyy-MM-dd hh:mm:ss y otros formatos)

Formato del método de encapsulación

//date指的是new Date(),fmt是格式化的格式
 format=(date,fmt)=>{
    
    
    var o = {
    
     
        "M+" : date.getMonth()+1,                 //月份 
        "d+" : date.getDate(),                    //日 
        "h+" : date.getHours(),                   //小时 
        "m+" : date.getMinutes(),                 //分 
        "s+" : date.getSeconds(),                 //秒 
        "q+" : Math.floor((date.getMonth()+3)/3), //季度 
        "S"  : date.getMilliseconds()             //毫秒 
    }; 
    //(y+)匹配多个y,比如yyyy
    if(/(y+)/.test(fmt)) {
    
    
         // RegExp.$1是RegExp的一个属性,指的是与正则表达式匹配的第一个 子匹配(以括号为标志)字符串
            fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
    
    
        if(new RegExp("("+ k +")").test(fmt)){
    
    
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
   }
   console.log(format(new Date(),'yyyy/MM/dd'))//2022/09/03
   console.log(format(new Date(),'yyyy/MM/dd hh:mm:ss'))//2022/09/03 16:11:41
   console.log(format(new Date(),'mm:ss'))//18:28

También puede agregar directamente el método de formato al prototipo de Fecha


Date.prototype.format = function(fmt) {
    
     
     var o = {
    
     
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
    
    
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
    
    
        if(new RegExp("("+ k +")").test(fmt)){
    
    
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}
//使用
console.log(new Date().format("yyyy:MM:dd")//2022:09:03
2. Convierta la marca de tiempo al formato de año, mes y día
//时间戳转换为yyyy-MM-dd hh:mm:ss
//timestamp(秒为单位)时间戳
export function format(timestamp) {
    
    
  var date = new Date(timestamp * 1000);
  var Y = date.getFullYear() + "-";
  var M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  var D =
    (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  var h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";

  var m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  var s =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
}

O utilícelo junto con el formato después de obtener la fecha

3. Convertir tiempo en marca de tiempo
var date = new Date('2022-9-03');
//方式一,得到的是毫秒
var time1 = date.getTime();
//方式二,得到的是毫秒
var time2 = date.valueOf();

Nota: las marcas de tiempo de Unix son la cantidad de segundos desde el 1 de enero de 1970 (medianoche UTC/GMT)

Supongo que te gusta

Origin blog.csdn.net/CYL_2021/article/details/126679340
Recomendado
Clasificación