如何在jQuery DateTimePicker中获取选中日期的星期几
解决方案
选项1:在日期输入框中直接显示星期信息
修改onSelect回调函数,添加星期计算逻辑,同时明确日期选择器的格式参数,最后更新输入框显示内容:
// 定义中文星期数组,对应getDay()返回的0(周日)到6(周六) const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; $("input.Date").datepicker({ dateFormat: 'mm/dd/yy', // 匹配当前显示格式,自动转为四位年份 onSelect: function (dateText, inst) { const selectedDate = new Date(dateText); const weekday = weekdays[selectedDate.getDay()]; // 更新输入框为「日期 星期」格式 $(this).val(`${dateText} ${weekday}`); // 保留原有日期拆分逻辑 $("#" + this.id + "_month").val(selectedDate.getMonth() + 1); $("#" + this.id + "_day").val(selectedDate.getDate()); $("#" + this.id + "_year").val(selectedDate.getFullYear()); $("#" + this.id + "_changeTime").val(Date.now()).trigger('change'); }, changeMonth: true, changeYear: true, yearRange: '1900:2050', showButtonPanel: true, showOn: 'both', buttonText: 'Date', buttonImageOnly: true, closeText: 'Close', showAnim: '', dayNamesShort: true });
选项2:将星期信息存入隐藏字段
先在页面中添加对应隐藏字段(假设日期输入框ID为xxx,则隐藏字段ID设为xxx_weekday):
<input type="hidden" id="xxx_weekday">
再修改onSelect函数,把计算出的星期存入隐藏字段:
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; $("input.Date").datepicker({ onSelect: function (dateText, inst) { const selectedDate = new Date(dateText); const weekday = weekdays[selectedDate.getDay()]; // 将星期写入对应隐藏字段 $("#" + this.id + "_weekday").val(weekday); // 保留原有日期拆分逻辑 $("#" + this.id + "_month").val(selectedDate.getMonth() + 1); $("#" + this.id + "_day").val(selectedDate.getDate()); $("#" + this.id + "_year").val(selectedDate.getFullYear()); $("#" + this.id + "_changeTime").val(Date.now()).trigger('change'); }, changeMonth: true, changeYear: true, yearRange: '1900:2050', showButtonPanel: true, showOn: 'both', buttonText: 'Date', buttonImageOnly: true, closeText: 'Close', showAnim: '', dayNamesShort: true });
注意事项
- 中文星期数组顺序需和
getDay()返回值对应(0=周日,6=周六),若需调整星期起始(如周一为第一天),可自行修改数组顺序或计算逻辑。 - 若当前日期格式不是
mm/dd/yyyy,需同步修改dateFormat参数,确保new Date(dateText)能正确解析日期。
内容的提问来源于stack exchange,提问作者Keith
相关产品推荐
相关产品推荐

