js格式化日期,并获取上一天,下一天的日期

JavaScript 小智 857℃ 0评论

获取“yyyy-MM-dd HH:MM:SS”格式的日期,并支持上一天,下一天的切换

//格式转换
function format(date){
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	
	var formatDate = date.getFullYear() + seperator1 + month + seperator1 + 
			formatLength(date.getDate()) + " " + formatLength(date.getHours()) + 
			seperator2 + formatLength(date.getMinutes())
			+ seperator2 + formatLength(date.getSeconds());
	return formatDate;
}

function formatLength(temp){
	if (temp >= 0 && temp <= 9) {
		temp = "0" + temp;
	}
	return temp;
}

//当前日期
function current() {
	var currentDate = new Date();
	document.getElementById("current").innerHTML = format(currentDate);
}
//前一天
function previous(){
	var currenttemp = document.getElementById("current").innerHTML;

	if(currenttemp.length > 0){
		// /g替换所有
		var tem = currenttemp.substring(0,10).replace(/-/g, "/");
	}else{
		var temp = "20161207";
		var tem = temp.substring(0,4) + "/" + temp.substring(4,6) + 
		"/" + temp.substring(6,8);
	}
	
	
	var d = new Date(tem);
	
	d.setTime(d.getTime()-24*60*60*1000);

	document.getElementById("current").innerHTML = format(d).substring(0,10) + 
	format(new Date()).substring(10);
}
//后一天
function next(){
	var currenttemp = document.getElementById("current").innerHTML;

	if(currenttemp.length > 0){
		var tem = currenttemp.substring(0,10).replace(/-/g, "/");
	}else{
		var temp = "20161207";
		var tem = temp.substring(0,4) + "/" + temp.substring(4,6) + 
		"/" + temp.substring(6,8);
	}
	
	var d = new Date(tem);

	d.setTime(d.getTime()+24*60*60*1000);
	document.getElementById("current").innerHTML = format(d).substring(0,10) +
	format(new Date()).substring(10);
}

本文固定链接:心知博客 » js格式化日期,并获取上一天,下一天的日期
本站内容除特别标注外均为原创,欢迎转载,但请保留出处!

喜欢 (2)
发表我的评论
取消评论
表情

请填写您的昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址