[英]How to get Start and End date given the week number in jQuery datepicker
jQuery DatePicker has the ability to return weeknumber based on a selected date. jQuery DatePicker能够根据所选日期返回周数。
How can I get Start and End Date of that weeknumber based on a selected date? 如何根据所选日期获得该周号的开始日期和结束日期?
Currently I have following code, I but I would appreciate any tips to improve this for above requirement. 目前,我有以下代码,但我希望为上述要求提供一些改进的技巧。
<script type="text/javascript">
$(document).ready(function () {
$('#' + '<%= weekTBox.ClientID %>').datepicker({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
constrainInput: true,
showWeek: true,
firstDay: 1,
showOtherMonths: true,
selectOtherMonths: true
,onSelect: function (dateText, ui) {
//desired functionality should be here...
$this.val($.datepicker.iso8601Week(new Date(dateText)));
}
});
});
</script>
Given a year and week number, the following returns a date that is the Monday at the start of the week (assuming you want weeks starting on Monday). 给定年份和星期数,以下代码返回一个日期,该日期是每周开始时的星期一(假设您希望星期从星期一开始)。
Week numbers are based on the week that has the first Thursday of the year, so this function looks at 1 January and determines the first day of week 1 (Monday), then adds days for the number of weeks * 7 to get the first Monday of the subject week. 星期数基于一年中第一个星期四的星期,因此此功能查找1月1日,并确定星期1的第一天(星期一),然后将星期数* 7加到第一个星期一。主题周。 The end of the week is the following Sunday, so just add 7 to the date.
周末是下一个星期日,因此只需在日期上加上7。
// Returns a Date object for Monday at the
// start of the specified week
function dateFromWeekNumber(year, week) {
var d = new Date(year, 0, 1);
var dayNum = d.getDay();
var diff = --week * 7;
// If 1 Jan is Friday to Sunday, go to next week
if (!dayNum || dayNum > 4) {
diff += 7;
}
// Add required number of days
d.setDate(d.getDate() - d.getDay() + ++diff);
return d;
}
console.log(dateFromWeekNumber(2014, 1)); // Mon 30 Dec 2013
console.log(dateFromWeekNumber(2016, 1)); // Mon 04 Jan 2016
console.log(dateFromWeekNumber(2014, 30)); // Mon 21 Jul 2014
You may want to add validation, eg that week is an integer greater than zero and less than 54. 您可能要添加验证,例如,该周是一个大于零且小于54的整数。
Modified to return Monday of week number. 修改为返回星期几的星期一。
$( "#datepicker" ).datepicker({
showWeek: true,
firstDay: 1,
onSelect: function(date){
var d = new Date(date);
var d1 = new Date(date);
var index = d.getDay();
// console.log(index)
if(index == 0) {
d.setDate(d.getDate() - 6);
d1.setDate(d1.getDate() - 2);
}
else if(index == 1) {
d.setDate(d.getDate());
d1.setDate(d1.getDate()+4);
}
else if(index != 1 && index > 0) {
d.setDate(d.getDate() - (index - 1));
d1.setDate(d1.getDate() + (index + 1));
//console.log(d.getDate() - (index - 1))
}
console.log('Week number::'+$.datepicker.iso8601Week(new Date(d)));
console.log("start date::"+d)
console.log("End date::"+d1)
//$(this).val(d);
}
});
});
I think This will help u.. 我认为这对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.