欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

计算周一、周天、月初、月末日期

程序员文章站 2022-05-15 09:49:45
...
<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
		<title></title>
	</head>

	<body>
		<button onclick="mydateFormat()">敲我</button>
		<hr>
		<input type="text" id="weekFirst" placeholder="周一">
		<input type="text" id="weekLast" placeholder="周日">
		<input type="text" id="monthFirst" placeholder="月初">
		<input type="text" id="monthLast" placeholder="月末">
		<script>
			function mydateFormat() {
				$("#weekFirst").val(weekFirstDay());
				$("#weekLast").val(weekLastDay());
				$("#monthFirst").val(getMonthFirstDay());
				$("#monthLast").val(getMonthLastDay());
			}
			// 获取本月第一天日期
			function getMonthFirstDay() {
				var now = new Date();
				var month = ("0" + (now.getMonth() + 1)).slice(-2);
				var monthFisrtDate = now.getFullYear() + "-" + (month) + "-01";
				return monthFisrtDate;
			}
			// 获取本月最后一天日期
			function getMonthLastDay() {
				var now = new Date();
				var nextMonthFirstDate = now.getFullYear() + "-" + ("0" + (now.getMonth() + 2)).slice(-2) + "-01";
				var monthLastDate = new Date((new Date(nextMonthFirstDate)).getTime() - 24 * 60 * 60 * 1000);
				return formatDay(monthLastDate);
			}
			// 获取本周第一天的日期
			function weekFirstDay() {
				d = new Date();
				var time = d.getTime();
				var StartTime = time - (d.getDay() - 1) * 24 * 60 * 60 * 1000;
				var weekFirstDay = new Date(StartTime);
				return formatDay(weekFirstDay);
			}
			// 获取本周最后一天日期
			function weekLastDay() {
				d = new Date();
				var time = d.getTime();
				var EndTime = time + (7 - d.getDay()) * 24 * 60 * 60 * 1000;
				var weekLastDay = new Date(EndTime);
				return formatDay(weekLastDay);
			}
			// 格式化日期
			function formatDay(date) {
				var d = date;
				var day = ("0" + d.getDate()).slice(-2);
				var month = ("0" + (d.getMonth() + 1)).slice(-2);
				return d.getFullYear() + "-" + (month) + "-" + (day);
			}
		</script>
	</body>

</html>

相关标签: js 日期