格式化时间戳样式-获取前一天日期格式-js代码

// 时间格式转换
function formatDate(t) {
	var time = new Date(t);
	var year = time.getFullYear();
	var month = time.getMonth() + 1;
	var date = time.getDate();
	var hour = time.getHours();
	var minute = time.getMinutes();
	var second = time.getSeconds();
	month = month < 10 ? "0" + month : month;
	date = date < 10 ? "0" + date : date;
	hour = hour < 10 ? "0" + hour : hour;
	minute = minute < 10 ? "0" + minute : minute;
	second = second < 10 ? "0" + second : second;
	return year + "-" + month + "-" + date + " " + hour + ":" + minute;
}

//函数方法版
function formatDate1(date) {
	date = new Date(date);
	return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
}

console.log(formatDate(1605685316699));
console.log(formatDate1(1605685316699));

format方法 

原生js和jquery都不能直接用new Date().format('yyyy-MM-dd')

 js引入date.format.js 下载地址

<script src="date.format.js"></script>

或者写方法使用

Date.prototype.format = function(format)
{
 var o = {
 "M+" : this.getMonth()+1, //month
 "d+" : this.getDate(),    //day
 "h+" : this.getHours(),   //hour
 "m+" : this.getMinutes(), //minute
 "s+" : this.getSeconds(), //second
 "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
 "S" : this.getMilliseconds() //millisecond
 }
 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;
}
var date1 = new Date().format('yyyy-MM-dd');
console.log(date1);

 获取前一天日期

//获取前一天日期
function time(){
  let time = (new Date).getTime() - 24 * 60 * 60 * 1000;
  let yesday = new Date(time); // 获取的是前一天日期
  yesday = yesday.getFullYear() + "-" + (yesday.getMonth()> 9 ? (yesday.getMonth() + 1) : "0" + (yesday.getMonth() + 1)) + "-" +(yesday.getDate()> 9 ? (yesday.getDate()) : "0" + (yesday.getDate())); //字符串拼接转格式:例如2018-08-19
},

 

posted @ 2022-12-26 17:04  JackieDYH  阅读(5)  评论(0编辑  收藏  举报  来源