[英]JavaScript-set date to Friday before
I am using ASP.Net AJAX Calendar Extender to set a date in a textbox. 我正在使用ASP.Net AJAX Calendar Extender在文本框中设置日期。 Whilst it is simple enough to get the date from the user's selection in JavaScript, I am struggling to set the date in to a Friday.
从JavaScript中的用户选择中获取日期非常简单,但我正在努力将日期设置为星期五。
In detail, what I am trying to do is for example, if a user selected a date which turns out to be a Tuesday, what I want to show in the textbox, is not that week's Friday, but the Friday before, ie the one that was 3 days before. 详细地讲,例如,如果用户选择的日期竟然是星期二,那么我想在文本框中显示的不是那个星期的星期五,而是那个星期五之前的星期五。那是三天前
What I have achieved is to get the next Friday, ie the one coming up, but I have played around with the code in various ways to try and achieve what I want - can someone please help? 我所取得的成就是下一个星期五,也就是即将到来的那个星期五,但是我以各种方式尝试使用代码来尝试实现自己想要的目标-有人可以帮忙吗?
Thanks 谢谢
dayToMtceSet = 5;
distance = (dayToMtceSet - currentDay) % 7;
toDate = toDate.setDate(toDate.getDate() + distance);
document.getElementById('<%= txtFromDate.ClientID%>').value = formatDate(toDate);
toDateSet = new Date(toDate);
toDateSet = toDateSet.setDate(toDateSet.getDate() + 6);
document.getElementById('<%= txtToDate.ClientID%>').value = formatDate(toDateSet);
With pure javascript jsFiddle : 使用纯JavaScript jsFiddle :
if (date.getDay() === 5) {
console.log(date);
} else {
var beforeOneWeek = new Date(date.getTime() - 60 * 60 * 24 * 7 * 1000),
day = beforeOneWeek.getDay(),
diffToFriday = day > 5 ? 6 : 5 - day;
date.setDate((date.getDate() - 7) + diffToFriday);
console.log(date);
}
You could also use date.js 您也可以使用date.js
var date = Date.today();
if (date.getDay() === 5) {
date = Date.today();
} else {
date = date.moveToDayOfWeek(5, -1) // 5 is Friday, -1 is back one week
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.