SQL Query using Date retrieves Datetime values in a Node application connected to MSSQL

I am currently using version 6.3.1 of node mssql. My query involves multiple columns that are of type date. When querying in node mssql, the output for all Date columns is in this format: 2020-10-20T00:00:00.000Z However, when I execute the same query in Azure Data Studio, I get: 2020-10-20

The issue arises when I need to update the database as I encounter an error using the YYYY-MM-DD format. Is there a method to update the database without having to manually check each field if it's a date and then append "T00:00:00.000Z" to it?

Current code snippet:

// Executed at server startup

const sql = require('mssql')

const poolPromise = sql.connect({
  server: process.env.SQL_SERVER,
  user: process.env.SQL_USER,
  password: process.env.SQL_PASSWORD,
  database: process.env.SQL_DATABASE
})

// Executed during query operation

async function updateSqlRecord(fields) {
// Adding fields below for demonstration
  let fields = {id: 1, name: 'test', date: '2020-10-12' }

  let database = process.env.SQL_DATABASE
  let table = 'Test'
  let querystring = `UPDATE [${database}].[dbo].[${table}] SET `

  Object.entries(fields).forEach(field => {
    const [key, value] = field;
    querystring += `${key} = '${value}', `
  });

  querystring = querystring.slice(0, -2)
  querystring += ` WHERE projektNr = ${fields.projektNr}`
  try {
    let pool = await poolPromise
    let result = await pool.request()
      // .input('projektNr', sql.Int, value)
      .query(querystring)
    console.log(result)
    return result.rowsAffected
  } catch (err) {
      console.log('SQL request Error',err)
  }

}

Answer №1

Consider utilizing the moment.js library for date parsing before inserting it into your database.

var moment = require('moment');
...
var formattedDate = moment(myDate).format('YYYY/MM/DD HH:MM:SS').toISOString();

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

Dragging a Google Maps marker causes a border to appear around a nearby marker

Recently, I added a main draggable marker to the map. However, an unusual issue arises when dragging this marker - a blue outline appears around one of the existing markers on the map. This behavior is puzzling as it seems to be triggered by a click event ...

After successfully creating an account, the displayName consistently appears as null

I have a Vue project that utilizes Firebase as the backend. User registration is done using email and password. Below is the method used in Firebase: firebase.auth() .createUserWithEmailAndPassword(this.user.email, this.user.password) . ...

Customize the MUI (JoyUI) Autocomplete feature in React using react-hook-form to display a unique value instead of the label

Currently, I am in the process of creating a form that includes JoyUI (material) autocomplete and react-hook-form functionality. The array of objects I am using for my options looks like this: [ { label: "Todo", param: "TODO" }, ...

extract information from a document and store it in an array

As I delve into the realm of programming, I find myself grappling with the best approach to extract data from a file and store it in an array. My ultimate aim is to establish a dictionary for a game that can verify words provided by players. Despite my no ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

The Date validation script in Javascript is malfunctioning

I encountered an issue where the script I used in my HTML file didn't work as expected. The purpose of this script was to prevent users from submitting a date greater than today's date. Interestingly, when I copied the same script to another HTML ...

Encountering JSON parsing errors while using fetch() POST requests in Express

Currently, I am experimenting with HTTP requests and my main focus is on sending a POST request. The data for this request is coming from an input field and I am using fetch() to send it to a URL on my local host which is set up with express. My goal is to ...

Working with requests and responses in functions in Node.js

When I swap the positions of req and res, for example (res,req)=>{ res.send();}, the server throws an error saying that res.send is not a function. Are we limited in how we position the req and res objects? Why does it show an error that res.send() is ...

Is it possible to compare escaped data with the unescaped value of a select box in JavaScript?

On my webpage, I have a functionality that involves fetching select box options through an AJAX request. I then create the select box based on this data, and later use the selected option to retrieve additional information from the response received via AJ ...

The Quirks of jQuery's .load() Method

On my website, I am incorporating a basic jQuery script to load content from one part of a webpage into the 'display container' on the same page. The content being loaded consists of multiple divs enclosed within an outer <div> that is hid ...

What could be causing this `even` function to malfunction when utilizing getElementById?

Need assistance with utilizing document.getElementById? Let's take a look at this code snippet: function even() for (i = 0; i < 10; i++) { if (i % 2 == 0) { alert(i); } } document.getElementById("even").innerHTML = i + &apos ...

Would you be able to clarify why the run() function is giving me an error when I try to return {1,3}, but it works fine when I return {a,b} in

I'm really confused as to why the return {1,3} in the run() function is throwing an error when it works just fine for return {a,b} in the fun() function function fun(){ let a = 10; let b = 20; return {a, b}; } ...

Locating a Guild Member using their Alias

I need help locating a GuildMember using their nickname. The nickname is linked to their Roblox name upon joining the server, and I've configured a webhook to transmit a message in a specific channel containing their username and other related details ...

Adjust the size of an input field in jquery or javascript based on user input

Ensure that an input text box can only contain a maximum of 13 numbers, but if the user enters a 14th number as a decimal point, then allow up to 16 numbers. HTML: <input type="text" maxlength="15" onkeyup="checkCurrency(this)"/> Script: func ...

Why does the del command delete the parent folder as well?

I am looking to remove all files within the ./dist/* directory while leaving the ./dist folder itself untouched (it should be empty once the task completes). const del = require('del'); gulp.task('clean:dist', function(cb){ del([ ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

Error: The options object provided for CSS Loader is not valid and does not match the API schema. Please make sure to provide the correct options when

Summary My Nuxt.js project was created using the command yarn create nuxt-app in SPA mode. However, I encountered an error after installing Storybook where running yarn dev resulted in failure to start the demo page. ERROR Failed to compile with 1 errors ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.usercount; columnDefs: [{ nam ...

How can you toggle the visibility of a div based on detecting a specific class while scrolling?

My webpage features a sticky header that gains an extra .header-scrolled class when users scroll down. I am looking to switch the logo displayed in the header once it has been scrolled. Below is a simplified version of my HTML code: <header class=".he ...