我需要在js中检索当前日期的第n个工作日。像第一个星期日,第二个星期天
var d = new Date(); var weekDay = d.getDay();
这里的周日给我4意味着它的星期三(第3个星期三)。到目前为止它很好。
从周日开始,我可以说是星期三。如何计算" 3rd"这个星期三的指数?
谢谢
答案 0 :(得分:0)
var today = new Date();
在更大的背景下,您可以展示从工作日,日期,年份等等所有内容!我将在下面提供一个代码位。该代码以HTML格式显示动态时钟/日期。
您可以按照自己的方式格式化,并选择要显示的变量!这是与此处的代码相同的代码:Other thread/question
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today=new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = "Date: " + day + "/" + month + "/" + year + " " + "Clock: " + h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
这是你的意思吗?
答案 1 :(得分:0)
像这样的东西
function getNth(dat) {
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','saturday'],
nth = ['st', 'nd', 'rd', 'th', 'th'],
d = dat ? dat instanceof Date ? dat : new Date(dat) : new Date(),
date = d.getDate(),
day = d.getDay(),
n = Math.ceil(date / 7);
return n + nth[n-1] + ' ' + days[day];
}
document.body.innerHTML = '' +
'today ....: ' + getNth() + '<br>' +
'1/31/2015 : ' + getNth('1/31/2015') + '<br>' +
'1/16/2015 : ' + getNth('1/16/2015');
&#13;
body {font-family: monospace}
&#13;
答案 2 :(得分:0)
根据我的理解,您希望从今天开始的第1天,第2个星期日/星期一是什么日期。如果是,那么你可以使用这个
//consider sun=o,mon=1,....,sat:6
function getWeekday(n,day)
{
var today = new Date();
var presentDay = today.getDay();
var presentTime = today.getTime();
if(day < presentDay)
{
day = day +6;
}
var diff = day - present day;
var daysAfter = (n-1)*7 + diff;
var timeAfter = presentTime+daysAfter*86400000;
var next date = new Date(timeAfter);
}
// if you want to get 1st sunday from today just call this
var sunday1 = getWeekday(1,0)
// to get second monday from today
var monday2 = getWeekday(2,1)