JavaScript 时间戳转日期,动态格式
JavaScript 时间戳转日期,动态格式
引用案例:
this.handleDateTime(new Date()) //2021-07-29 15:23:36 this.handleDateTime(new Date(),'yyyy/mm/dd hh:MM:ss') //2021/07/29 24:47 this.handleDateTime(new Date(),'mm/dd MM:ss') //07/29 34:40 this.handleDateTime(new Date(),'hh:MM:ss') //15:35:25 this.handleDateTime(1626678335000,'mm/dd hh:MM:ss') //07/19 15:05:35 this.handleDateTime(1626678335000,'yyy/mm/dd hh:MM:ss') //2021/07/19 15:05:35
/** *timestamp:时间戳 *formateType:需要转换的格式 */ handleDateTime(timestamp,formateType){ let date=new Date(timestamp); let line='-' let value=''; let format={ yyyy:date.getFullYear(), mm:date.getMonth()+1, dd:date.getDate(), hh:date.getHours(), MM:date.getMinutes(), ss:date.getSeconds(), } for (let i in format){ if(format[i]<10){ format[i]="0"+format[i] } } if(formateType){ let m=false; let y=false if(formateType.split("/").length>1){ line='/' } if(formateType.indexOf('yyyy')!=-1){ value+=format.yyyy; m=true y=true } if(formateType.indexOf('mm')!=-1){ value+=y?line+format.mm:format.mm; m=true y=true } if(formateType.indexOf('dd')!=-1){ value+=y?line+format.dd:format.dd; m=true } if(formateType.indexOf('hh')!=-1){ value+=m?(" "+format.hh+":"):(format.hh+":"); m=false } if(formateType.indexOf('MM')!=-1){ value+=m?" "+format.MM:format.MM; m=false } if(formateType.indexOf('ss')!=-1){ value+=m?" "+format.ss:":"+format.ss; m=false } }else{ value=format.yyyy+line+format.mm+line+format.dd+" "+format.hh+":"+format.MM+":"+format.ss } return value }