Home > Software design >  Time changes after toLocaleTimeString()
Time changes after toLocaleTimeString()

Time:01-20

I'm using a google sheets script, which on the click of a button will add values to two fields. The first will contain the date, the second the time. For this, I use this piece of code:

  var timestamp = new Date();
  var date = Utilities.formatDate(timestamp, "GMT 1", "dd/MM/yyyy");
  var time = timestamp.toLocaleTimeString('nl-BE');

Now, the issue is that the time is off by 6 hours. The timestamp value does contain the correct time, the date variable gets the correct date, but the time seems to differ 6 hours after the 'toLocaleTimeString() function.

CodePudding user response:

Use Utilities.formatDate() for time as well, like this:

  const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); // or 'GMT 1'
  const timestamp = new Date();
  const dateString = Utilities.formatDate(timestamp, timezone, 'dd/MM/yyyy');
  const timeString = Utilities.formatDate(timestamp, timezone, 'HH:mm:ss');
  console.log(`date and time in ${timezone}: ${dateString} ${timeString}`);
  • Related