获取当前时间,获取前几天,后几天时间

1. 获取当前时间

var date = new Date();
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();
console.log(Y+M+D+h+m+s); //2023-04-28 09:38:23

2.获取昨天,明天的时间

//date:当前时间,day:昨天就-1,明天就+1
getNextDate(date, day) { 
    var dd = new Date(date);
	dd.setDate(dd.getDate() + day);
	var y = dd.getFullYear();
	var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
	var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.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;
}

你可能感兴趣的:(javascript,前端)