我在网上搜索过,发现脚本可以获得一年中的周数。然而,我的计数是不同的。下图是我想要的周数。当我使用'1/5/2015'测试时,我的代码得到的周数是2,但是在我的要求中,周数应该是1。有人可以帮助我吗?提前谢谢。
找到了javascript有我的代码:
function myWeekNumber(thisDate) {
var dt = new Date(thisDate)
var onejan=new Date(dt.getFullYear(), 0, 2);
return Math.ceil((((dt - onejan) / 86400000) + onejan.getDay() + 1) / 7); }
答案 0 :(得分:0)
您尝试实施的算法似乎是:
在这种情况下,最好使用UTC方法来避免夏令时问题:
function getWeekNumberNonISO(d) {
// Create UTC equivalent for 23:59:59.999 on the passed in date
var sat = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(),23,59,59,999));
// Set to Saturday at end of week
sat.setUTCDate(sat.getUTCDate() + 6 - sat.getUTCDay());
// Get first day of year
var firstDay = new Date(Date.UTC(sat.getUTCFullYear(), 0, 1));
// Set to Sunday on or before, i.e. first day of first week in year
firstDay = firstDay.setUTCDate(firstDay.getUTCDate() - firstDay.getUTCDay());
// Week number is difference in dates divided by ms/week rounded
return Math.round((sat - firstDay)/(6.048e8));
}
// Get week number for Mon 5 Jan 2015
console.log(getWeekNumberNonISO(new Date(2015,0,5))); // 2
// Get week number for Sat 31 Dec 2011
console.log(getWeekNumberNonISO(new Date(2011,11,31))); //53
// Get week number for Sat 1 Jan 2011
console.log(getWeekNumberNonISO(new Date(2011,0,1))); // 1
// Get week number for Sun 2 Jan 2011
console.log(getWeekNumberNonISO(new Date(2011,0,2))); // 2

答案 1 :(得分:-2)
Js具有函数inbulid函数,可用于从一周的给定日期getweek()中获取日期。
var week=date.getWeek()