How to convert a JavaScript date to SQL date object?

Sometimes, we want to convert a JavaScript date to SQL date object.

In this article, we’ll look at how to convert a JavaScript date to SQL date object.

How to convert a JavaScript date to SQL date object?

To convert a JavaScript date to SQL date object, we can use the JavaScript date’s toLocaleString method.

For instance, we write:

const date = (new Date(2022, 1, 1)).toLocaleString("en-US")
console.log(date)

to call toLocaleString with 'en-US' to convert return a date string formatted for the US English locale.

Therefore, date is '2/1/2022, 12:00:00 AM'.

Conclusion

To convert a JavaScript date to SQL date object, we can use the JavaScript date’s toLocaleString method.