使用javascript从今天的日期找到第4个星期五

时间:2012-08-26 03:24:32

标签: javascript date

我一直在努力制作一个快速参考表供工作,并且一直在使用它作为开始尝试学习JavaScript的一种方式。 我一直难以理解如何在当前日期的第4个星期五(或任何一天)以dd / mm / yyyy显示日期。如果有人能指出我正确的方向,那将非常感激

1 个答案:

答案 0 :(得分:2)

这个想法是使用setDate()来添加日期。以下代码应该为您设置:

<html>
<script>

// You might want to make a function out of this, btw.

dayWeWant = 5; // Friday 
today = new Date();

// So you want the fourth friday, eh?

// remember friday is 5 for getDay

if (today.getDay() < dayWeWant)  {  nextFri =  7 - (today.getDay() -  dayWeWant) }  // days remaining
else  { nextFri = dayWeWant - today.getDay(); }

// If today IS friday, you want 4 instead of 3. Of course,
// 3 can also be made into a "constant" variable, such as howManyWeeks or something

threeMore = nextFri + 3 * 7; // three more weeks

nextDate = new Date();

nextDate.setDate(today.getDate() + threeMore);

   alert (nextDate);





</script>
</html>

代码有意被很好地注释,并且效率不高(并且常数不好 - 你可以将它们变成某些函数的参数) - 但这样做。从这里开始,可以进行微小的优化(但不是可读的,IOHO)

希望这有助于,

TG