时间转换是开发中比较常用的方法,所以我整理了一下
(做了了一个前端时间转换小工具,功能比较齐全:github:https://github.com/date-convert/date-convert ,可以查看详细使用方法,欢迎交流!) 构造函数
class dateConvert {
constructor(){
Date.prototype.Format = function(format){
const week = this.getDay();
let weekStr = '';
switch(week){
case 0:
weekStr = '星期日';
break;
case 1:
weekStr = '星期一';
break;
case 2:
weekStr = '星期二';
break;
case 3:
weekStr = '星期三';
break;
case 4:
weekStr = '星期四';
break;
case 5:
weekStr = '星期五';
break;
case 6:
weekStr = '星期六';
break;
}
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"w": weekStr,//week
}
if(/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
}
}
return format;
}
}
convert(value,format){
if(format == 'y-m-d h:m:s'){
var myDate= new Date(value).Format("yyyy-MM-dd hh:mm:ss");
return myDate;
}else if(format == 'y-m-d'){
var myDate= new Date(value).Format("yyyy-MM-dd");
return myDate;
}else{
var myDate= new Date(value).Format(format);
return myDate;
}
}
}
window.dateConvert = dateConvert
github:https://github.com/date-convert/date-convert ,可以查看详细使用方法,欢迎交流!
使用方法:
【插件库|js 时间戳、标准日期转换为年月日格式】//调用构造函数
let DC = window.dateConvert;
//实例化
let dateFun = new DC()
//常用方法的简写
let dateVal1 = dateFun.convert(new Date(),'y-m-d');
let dateVal2 = dateFun.convert(new Date(),'y-m-d h:m:s');
//常规方法示例
let dateVal3 = dateFun.convert(1323122444323,'yyyy-MM-dd hh:mm:ss w');
let dateVal4 = dateFun.convert(new Date(),'yyyy-MM-dd hh:mm:ss w');
let dateVal5 = dateFun.convert(new Date(),'yyyy-MM-dd hh:mm:ss');
let dateVal6 = dateFun.convert(new Date(),'yyyy-MM-dd');
//输出
document.write(dateVal1)
document.write('
')
document.write(dateVal2)
document.write('
')
document.write(dateVal3)
document.write('
')
document.write(dateVal4)
document.write('
')
document.write(dateVal5)
document.write('
')
document.write(dateVal6)