菜鳥在這里。對不起,如果這個問題很愚蠢。我正在為旅行目的撰寫腳本。給定星期幾,我需要獲取出發日期的開始和結束日期。以及給定開始/結束日期偏移量的退貨日期;呼叫函式后,出發日期也發生了變化。我無法理解我的錯誤。請幫忙。
var departstart=getNextDayOfTheWeek(3,0);
console.log("Departure from " departstart);
var departend=getNextDayOfTheWeek(3,0);
console.log("Departure to " departend);
var returnstart=getoffday(3,departstart);
// check again depature
console.log("Departure from " departstart);
// Has changed?!?!?!
console.log("Return from " returnstart);
var returnend=getoffday(3,departstart);
console.log("Return to " returnend);
// Gets a date of next day of the week
function getNextDayOfTheWeek(dayOfWeek, excludeToday = true, refDate = new Date()) {
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() !!excludeToday
(dayOfWeek 7 - refDate.getDay() - !!excludeToday) % 7);
return (refDate);
}
// Gets a date of diff day from given date
function getoffday(diff=0, workyday = new Date()) {
console.log("Inside function before execution " workyday);
workyday.setHours(0,0,0,0);
workyday.setDate(workyday.getDate() diff);
console.log("Inside function after execution " workyday);
return (workyday);
}
我想也許我不應該在函式中使用引數并定義區域變數,但這沒有幫助。
uj5u.com熱心網友回復:
如果您不想一直修改某個日期(就像現在一樣),您可以getoffday按如下方式修改您的函式:
// Gets a date of diff day from given date
function getoffday(diff=0, workyday = new Date()) {
// we create a new Date object with the value of the provided "workyday" param
// now we modify only this copied date - the provided date does not change
const dateCopy = new Date(workyday.getTime());
console.log("Inside function before execution " dateCopy);
dateCopy.setHours(0,0,0,0);
dateCopy.setDate(dateCopy.getDate() diff);
console.log("Inside function after execution " dateCopy);
return (dateCopy);
}
當然,您可以對您的getNextDayOfTheWeek函式使用相同的方法。通過這種方式,您可以獲得孤立的結果(不受函式外部變數值的影響)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536963.html
下一篇:Java日期格式不同的結果
