Loading episodes…
0:00 0:00

Set SQL Date from JavaScript

00:00
BACK TO HOME

Set SQL Date from JavaScript

10xTeam November 07, 2023 2 min read

To set a SQL date from JavaScript, you can use the following steps:

  1. Convert the JavaScript Date object to a string in the ISO 8601 format. This format is supported by all major SQL databases.
  2. Use the toISOString() method on the JavaScript Date object to convert it to a string in the ISO 8601 format.
  3. Replace the T character in the string with a space. SQL databases do not accept the T character in date strings.
  4. Set the SQL date column to the converted string.

Here is an example of how to set a SQL date from JavaScript:

const date = new Date();
const sqlDateString = date.toISOString().replace('T', ' ');
const sqlQuery = `UPDATE table_name SET date_column = '${sqlDateString}' WHERE id = 1`;

This SQL query will update the date_column column in the table_name table to the current date, as represented by the JavaScript Date object date.

Note: If you are using a library like Moment.js, you can use the format() method to convert the JavaScript Date object to a string in any desired format, including the ISO 8601 format.

Example using Moment.js:

import moment from 'moment';

const date = new Date();
const sqlDateString = moment(date).format('YYYY-MM-DD HH:mm:ss');
const sqlQuery = `UPDATE table_name SET date_column = '${sqlDateString}' WHERE id = 1`;

This SQL query will also update the date_column column in the table_name table to the current date, as represented by the JavaScript Date object date.


Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?