Set SQL Date from JavaScript

Set SQL Date from JavaScript

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.


  • Date: