初始化 "week" 控件值:
cs
//MVC部分
public ActionResult WeeklyList()
{
int weekNo = new GregorianCalendar().GetWeekOfYear(System.DateTime.Now, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
string DefaultWeek = DateTime.Now.Year + "-W" + weekNo;//2024-W42
ViewBag.DefaultWeek = DefaultWeek;//传值到html
return View();
}
//html部分
<input type="week" id="txt_week" class="my-css" value="@ViewBag.DefaultWeek" />
获取 "week" 控件所选中的星期一和星期日的值
cs
$(function () {
$("#btnSearch").click(function () {
var weekPicker = document.getElementById('txt_week');//type=week控件对象
var dateString = weekPicker.value;//控件值格式为: 'YYYY-WW',如:2024-W42
var year = parseInt(dateString.substr(0, 4), 10);//截取字符串"年"的部分:2024
var week = parseInt(dateString.substr(6, 2), 10);//截取字符串"第几周"的部分:42
//计算日期
var jsDate = new Date(year, 0, (week - 1) * 7);//生成日期
var dayOfWeek = jsDate.getDay();
var dayOffset = dayOfWeek === 1 ? 0 : 1 - dayOfWeek;
var monday = new Date(jsDate.setDate(jsDate.getDate() + dayOffset + 1));//星期一日期
var sunday = new Date(jsDate.setDate(monday.getDate() + 6));//星期日日期(星期一+6天)
console.log('星期一: ' + monday.toISOString().substr(0, 10));
console.log('星期日: ' + sunday.toISOString().substr(0, 10));
});
});
实际效果:
说明:
①我选中了week控件的:第42周(即2024年的第42个周,值为:2024-W42,格式为:yyyy-WW)
②截取字符串,获得年:2024,和年度第几周:42,开始计算日期,见js部分
③计算获得:第42周的,星期一是"2024-10-14",星期日是"2024-10-20"
④传递着两个日期值到MVC后台,对数据库进行日期范围的SQL查询