常用的js方法 - 日期时间格式化
常用的js方法 - 日期时间格式化
/**
* 时间格式化
* value = 时间戳 如不传,默认为当前时间戳
* type 是返回格式 如不传,默认为 1 只有日期
* type = 1 只有日期 2021-08-08
* type = 2 日期+时间 2021-08-08 19:30:08
*/
const formatDate = function(value,type=1) {
value = value?value:new Date().getTime();
var date = new Date();
date.setTime(value);
var month = date.getMonth() + 1;
if (month < 10)
month = "0" + month;
var day = date.getDate();
if (day < 10)
day = "0" + day;
var hours = date.getHours();
if (hours < 10)
hours = "0" + hours;
var minutes = date.getMinutes();
if (minutes < 10)
minutes = "0" + minutes;
var seconds = date.getSeconds();
if (seconds < 10)
seconds = "0" + seconds;
var resDate = date.getFullYear() + "-" + month + "-" + day;
var resTime = hours + ":" + minutes + ":" + seconds;
if(type==1){
return resDate;
}else{
return resDate + ' ' + resTime;
}
}