我正在寻找一种根据另一个星期表单元素的输入来填充星期表单元素的方法。我是Java语言的新手。
基本上,我需要获取c1和c2表格之间的星期差。 然后以相同的星期差自动填充d1和d2,但在c2之后的一周开始以d1开始。
示例:
c1 =“ 2018-W01”
c2 =“ 2018-W05”
应将d1和d2值设置为:
d1 =“ 2018-W06”
d2 =“ 2018-W10”
<input type="week" id="c1">
<input type="week" id="c2">
<input type="week" id="d1" readonly>
<input type="week" id="d2" readonly>
<script>
function myFunction() {
var d1 = document.getElementById("c1").value;
var d2 = document.getElementById("c2").value;
var year = d1.substring(0,4); //2018
var day1 = d1.substring(6,); //01
var day2 = d2.substring(6,); //05
var difference = day2 - day1; //5
document.getElementById("d1").value = d1 + difference; // ?
document.getElementById("d2").value = d2 + difference;
</script>
这段代码显然不起作用,但是显示了我的想法。 确实存在日期重叠两年的问题。 感谢您的帮助!
答案 0 :(得分:1)
尝试一下。
function myFunction(d1, d2) {
var year1 = parseInt(d1.substring(0, 4)); //2018
var year2 = parseInt(d2.substring(0, 4));
var yearDiff = Math.abs(year1 - year2);
var weeksInYears = 52 * yearDiff;
var day1 = parseInt(d1.substring(6, )); //01
var day2 = parseInt(d2.substring(6, )); //05
var difference = Math.abs(weeksInYears - (day2 - day1)); // handled dates with different years
var week1 = day2 + 1;
var week2 = week1 + difference;
week1 = ((week1 < 10 ? '0' : '') + week1);
week2 = ((week2 < 10 ? '0' : '') + week2)
var res = year1 + "-" + "W" + (week1); // ?
var res1 = year2 + "-" + "W" + (week2);
console.log(res, res1);}
答案 1 :(得分:0)
在JS中可以使用 https://momentjs.com/
此lib可解决您在该日期进行的任何操作
答案 2 :(得分:0)
更改这两行
var day1 = parseInt(d1.substring(6,)); //1
var day2 = parseInt(d2.substring(6,)); //5
然后它应该可以工作 但最好将其与Javascript日期结合使用->良好的参考https://www.w3schools.com/js/js_dates.asp
答案 3 :(得分:0)
尝试一下。
我想获得完整的年份(包含52周),所以我使用了
year2-(year1+1),
为了排除两个年份,然后我添加year1周(52-week1)
,然后添加第2周
var year1 = d1.substring(0,4); //2017
var year2 = d1.substring(0,4); //2018
var week1 = d1.substring(6,); //01
var week2 = d2.substring(6,); //05
let result = 52 *( year2 - (year1 + 1) ) + (52 - week1) + week2
答案 4 :(得分:0)
Hope, i could help you... I had use this in one of my project.
function diff_weeks(dt2, dt1){
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60 * 24 * 7);
return Math.abs(Math.round(diff));
}
dt1 = new Date(2014,10,4);
dt2 = new Date(2014,10,12);
console.log(diff_weeks(dt1, dt2));
dt1 = new Date("June 4, 1990 08:11:00");
dt2 = new Date("October 10, 2018 11:13:00");
console.log(diff_weeks(dt1, dt2));
答案 5 :(得分:0)
momentjs是您用于管理日期和时间的库。
它将帮助您以简单的方式管理日期的每个值。
var a = moment('2016-01-01');
var b = a.add(1, 'week');
a.format();
"2016-01-08T00:00:00-06:00"
请参见以下示例: