The date format in Google Sheets is being altered without manual intervention when data is input using Google APIs

Currently, I am undertaking a project that involves collecting data from an API, storing it in a matrix, and then setting that data in a Google Sheet using the Google-Sheets-APIv4 with Node.js. The two key elements in this API are object.start_date and object.end_date, which return date strings in the format such as "2021-09-22" (yyyy-mm-dd). My objective is to convert this date to the dd/mm/yyyy format. To achieve this, I have implemented the following function:

function changeDateFormat(dateString){
  let a=dateString.split('-');
  let t=a[0];
  a[0]=a[2];
  a[2]=t;
  //console.log(a.join('/'));
  return `${a.join('/')}`;
}

The code works correctly, and I've applied it in the following manner:

 let checkin=`${changeDateFormat(`${tenancy.start_date}`)}`;
 console.log(checkin);
 let checkout=`${changeDateFormat(`${tenancy.end_date}`)}`;
 console.log(checkout);

In the above code snippet, tenancy represents an object. The output displayed in the console matches the desired format, confirming that the date conversion algorithm functions appropriately.

Furthermore, my code for adding the data to the sheet is as follows:

await googleSheets.spreadsheets.values.append({
    auth,
    spreadsheetId,
    range:"MySheet!A2:AC",
    valueInputOption:"USER_ENTERED",
    resource: {values : newData} 
/*newData is a 2-D array where each row contains various data fields formatted as newData[i]=[propertyName,id,......,check-in,checkout,.......]*/
  });

Nevertheless, upon adding the data to the sheet, the date fields appear scattered - some displaying the preferred dd/mm/yyyy format while others retaining the original yyyy-mm-dd format, as depicted in this image https://i.stack.imgur.com/HvC5F.png

I'm currently unable to identify the issue within the code, even though no errors are apparent. The inconsistency of the output leaves me perplexed, with some cells being correctly formatted while others aren't. Could you suggest a viable workaround for this predicament? I'm willing to offer additional information or code snippets relating to the issue if necessary. Thank you!

Answer №1

It appears that your objective and circumstances are as follows.

  • You aim to format the cells to dd/mm/yyyy.
  • Your goal is to accomplish this using googleapis for Node.js.
  • You have already succeeded in retrieving and updating values for Google Spreadsheet using Sheets API.

Areas of Adjustment:

  • When values like
    [["2021-01-02", "02/01/2021"]]
    are inserted into the Spreadsheet utilizing the "spreadsheets.values.append" method in Sheets API with a valueInputOption set to USER_ENTERED, each value is entered as a date object but with potentially different number formatting.
  • To standardize the number format, I recommend setting the format to dd/mm/yyyy for the cells by utilizing the "spreadsheets.batchUpdate" method.

Once the aforementioned adjustments are made to your script, it will look like this.

Revised Script:

Please assign a value to sheetId.

await googleSheets.spreadsheets.values.append({
  auth,
  spreadsheetId,
  range: "MySheet!A2:AC",
  valueInputOption: "USER_ENTERED",
  resource: { values: newData },
});

const sheetId = "###";  // <--- Please specify the sheet ID for "MySheet".
const resource = {
  auth,
  spreadsheetId,
  resource: {
    requests: [
      {
        repeatCell: {
          range: {
            sheetId: sheetId,
            startRowIndex: 1,
            startColumnIndex: 12,
            endColumnIndex: 15,
          },
          cell: {
            userEnteredFormat: {
              numberFormat: {
                pattern: "dd/mm/yyyy",
                type: "DATE",
              },
              horizontalAlignment: "RIGHT", // <--- Added
            },
          },
          fields: "userEnteredFormat",
        },
      },
    ],
  },
};
await googleSheets.spreadsheets.batchUpdate(resource);
  • Executing the modified script above will change the number format of columns "M" to "O" to dd/mm/yyyy, aligning with your sample image.
  • If you need to tweak the format or range, feel free to adjust the script accordingly.
  • The batchUpdate method in the provided script applies the changes to all rows in columns "M" to "O." Therefore, running this method once should suffice in achieving your desired outcome.

References:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to effectively mocking functions during testing using jest and superagent

I've encountered an issue where I can't mock files and functions that are utilized in the API call handler. The API call is being simulated with superagent. Below is the test code: // users.itest.js const request = require('superagent&apos ...

npm encounters difficulty in initiating the server

I encountered some errors after running npm start in my angular project directory. It was working fine yesterday, but today when I entered the npm start command in my cmd prompt, it started showing errors: This is how my package.json file looks like: { ...

When the Drawer Component Backdrop is open, users will be blocked from interacting with the page

Is there a way to make the Drawer Component anchored at the bottom still interact with the content above it? I've tried using the persistent and permanent variants, but neither of them worked as they prevented any action when clicking outside the draw ...

Sending a massive video file to a node.js server and saving it in AWS S3 with ReactJS

I am currently in the process of creating an OTT platform, but I have encountered a problem while attempting to upload large files to the server. I initially attempted to store the file in a temporary folder using multer and then utilize aws-sdk s3.upload. ...

npm unable to retrieve Meteor package

When I attempted to install meteorite using nodejs v0.10.22 and npm v1.3.14, the installation failed with the following error: $ npm install meteorite npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

Is there a tool in Node.js to set up a new project, similar to the scaffolding feature in Visual Studio for C# projects

Is there a way to efficiently create a node.js project with TypeScript and Express, and embed an SPA client using React and Redux templates written in TypeScript as well? Is there a scaffolding tool available to streamline this process, similar to the ea ...

Using Node.js together with MQTT can sometimes result in errors like this: "Error: 'uncaughtException: Cannot set headers after they are sent to the client'"

Below is the code snippet for my fridge controller: const fs = require('fs'); const mqtt = require('mqtt'); const transporter = require('../params/mail') const winston = require('../params/log'); const User = require ...

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Using Vue.js: Execute a function with a delay, but start the delay over if there is any user input

Imagine a scenario where I have a form that is connected to an API and displays information based on user input. Whenever the user makes changes, such as adjusting the number of results per page, the component should react dynamically by loading new data. ...

The source 'http://localhost:3000' is not authorized to access the Twitter API

I am working on a web application that utilizes the Twitter API REST. On one of my pages, I have a list of Twitter accounts and a button to add a new account. When this button is clicked, it triggers a function in the Angular controller: // Function to ...

Bundle a library with Browserify instead of a single file

I'm currently exploring the use of npm libraries in browsers. Let's take the npm library uniq as an example. Right now, we have to start by writing the code that utilizes uniq locally: // main.js var unique = require('uniq'); var d ...

Consolidate various arrays of objects while eliminating duplicate items based on an optional property

Imagine having multiple arrays like these: const arr1 = [ { "id": "1", "type": "sales" }, { "id": "2", "type": "finance" } ] const arr2 = [ { "type": "s ...

Understanding the Difference Between WARN and ERR in npm Peer Dependency Resolution

I encountered a puzzling situation where two projects faced the same issue, yet npm resolved them differently: https://github.com/Sairyss/domain-driven-hexagon npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! W ...

In what location can event listeners be found in npm packages?

For a while now, I've been immersed in the world of coding as I work on creating my very own IRC bot using nodejs. This project serves as an invaluable learning experience for me, and as I navigate through the process, I constantly encounter event lis ...

Use the Fetch() function in Google Sheets to parse JSON data and organize it into

I have been attempting to utilize the Fetch() function in order to import a json file and populate multiple Google sheets. However, I have encountered some difficulties as my current knowledge is insufficient. The json file I am working with is constantly ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

Factorial calculating application on the web using Node.js

My goal is to create a nodejs program that calculates the factorial of numbers less than 30, a common exercise among beginner programmers. fact(0) = 1 fact(i) = i*fact(i-1) This time, I want the nodejs program to display the output directly on the client ...

Tips to successfully upload a large CSV file using an HTTP POST request

I am encountering an issue while attempting to transfer a significantly large CSV file from the client to the server within my MEAN stack application. The error message I keep receiving indicates that I am sending an excessive amount of data at once. Erro ...