2

我一直在尝试制作一份用于工作的快速参考表,并一直以此作为开始尝试学习 JavaScript 的一种方式。我一直不知道如何在 dd/mm/yyyy 中显示当前日期的第四个星期五(或任何一天)的日期。如果有人能指出我正确的方向,将不胜感激

4

1 回答 1

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

于 2012-08-26T03:35:41.623 回答