gpt4 book ai didi

javascript - 获取当前月的当前周

转载 作者:行者123 更新时间:2023-11-30 15:25:10 25 4
gpt4 key购买 nike

我找到了一个 javascript和一个 php script以全年为基础获取本月的当前一周。这很好,但我有点困惑。我想知道是否是当月的第 1、2、3、4 周而不是全年。我该如何解决?

javascript

/**
* Returns the week number for this date. dowOffset is the day of week the week
* "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
* the week returned is the ISO 8601 week number.
* @param int dowOffset
* @return int
*/
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};

用法

var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());

最佳答案

对于那些只想知道从 1 到 5 是哪一周的人来说,这适用于获取当月的当前周。

脚本

var d = new Date();
var date = d.getDate();
var day = d.getDay();

var weekOfMonth = Math.ceil((date + 6 - day)/7);

document.getElementById('week').value = weekOfMonth;

标记

<input type='text' id='week' value=''>

关于javascript - 获取当前月的当前周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43105674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com