0

I have a code to place the number of the day of the week, but it shows me one day less. What am I doing wrong? I can only use javascript. Any help will be appreciated.

HTML

<html>

 
  <input id="Day_number">Day of the Week Selected on DATE Input</label>
  <br>
  <label>Date</label>
  <input type="date" id="idDATE" onchange="set_day_number()">
  <script> 
   function set_day_number() {
   var dt = new Date(document.getElementById("idDATE").value);
   document.getElementById("Day_number").value = dt.getDay() ;
   }
  </script> 

GS

 var template = HtmlService.createTemplateFromFile('index');

 var htmlOutput = template.evaluate()
     .setSandboxMode(HtmlService.SandboxMode.IFRAME);

 return htmlOutput;
}
ONTIVER
  • 75
  • 5
  • [Did you read the doc ? ](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay) -> `Sunday...Saturday : 0...6` – Mister Jojo Jul 04 '23 at 02:55

1 Answers1

0

Date inputs return the date in the format YYY-MM-DD. The built–in parser will treat it as UTC. For a system set to a local time with a negative offset (i.e. west of Greenwich) the local date will be one day earlier. This is a well known issue, see Why does Date.parse give incorrect results?

One fix is to parse the timestamp as local using a simple function or library.

The following shows the:

  1. Value retrieved from the date input
  2. UTC date it is parsed as
  3. Equivalent local date for the system running the code
  4. Date for parsing the value as local

For systems with a positive offset (i.e. 0 or greater), the UTC and local dates (#2 and #3 respectively) will be the same. For systems with a negative offset, the local date will be one day earlier.

window.onload = () => {
  document.getElementById('theDate').addEventListener('change', showDate);
}

// date is timestamp in yyyy-mm-dd format
function parseISOLocal (date) {
  let [y, m, d] = date.split(/\D/);
  return new Date(y, m - 1, d);
}

function showDate(evt) {
  let d = evt.target.value;
  let date = new Date(d);
  console.log(
    `Input value  : ${d}\n` +
    `Default parse: ${date.toISOString()}\n` +
    `Local date   : ${date.toDateString()}\n` +
    `Local parse  : ${parseISOLocal(d).toDateString()}`
  );
}
Enter a date: <input type="date" id="theDate">
RobG
  • 142,382
  • 31
  • 172
  • 209