在JavaScript中自动计算日历周



我在html中有一个输入字段,我可以选择当前日期:

<input type="date" name="date" id="date"><br>
<input type="text" name="cw" id="calendarweek"> //here should appear automaticly the cw

在下一行中,我有另一个输入字段。该字段应该为我提供id为"日期"的输入字段的日历周。以上。我的目标是:当我选择日期时,日历周应该出现在"日期"下面的输入字段中。

我想在JavaScript中有一个函数。我只得到当前的日历…

我希望你能帮助我。我还在努力学习。

欢呼。

这是一个包含两个函数的演示,它们返回给定日期对象的年份中的星期。

这两个函数都是从网上抓取的,它们在评论中列出了相应的源代码。

特别是,第二个函数getWeek()附加到Date对象原型上,它需要一个偏移量作为参数:

getWeek()是一个更通用的周数函数,它将返回任何周定义的正确周数。参数dowOffset指定您的语言环境在美国开始一周的第几天。用户想要传递一个值0;欧洲和那些想要ISO 8601的人标准将传递值为1。当然,你可以选择开始星期在任何一天;getWeek()将根据周数定义周数一周的第三天。

当从日历中选择日期时,将检索日期,当此类事件发生时,将更新日历周的两个字段。

function onDatePicked(event){
const datePicked = new Date(event.target.value);
let o = getCalendarWeek(datePicked);      
document.getElementById('calendarweek').value = o;
document.getElementById('calendarweekIso').value = datePicked.getWeek(1);  
}
/**
* ->>>> https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php <<<<--
*/
function getCalendarWeek(date){  
var oneJan = new Date(date.getFullYear(),0,1);
var numberOfDays = Math.floor((date - oneJan) / (24 * 60 * 60 * 1000));
var result = Math.ceil(( date.getDay() + 1 + numberOfDays) / 7);  
return result;  
}
/**
* ->>>> https://www.epoch-calendar.com/support/getting_iso_week.html <<<<--
*
* 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.epoch-calendar.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;
};
<input type="date" name="date" id="date" onchange="onDatePicked(event);"><br>
<br>
<label>week number</label>
<input type="text" name="cw" id="calendarweek">
<br>
<label>ISO 8601 week number</label>
<input type="text" name="cw" id="calendarweekIso">

最新更新