Convert a JavaScript Date to SQL Server Date and Vice Versa

https://www.pexels.com/photo/brown-wooden-block-desk-calendar-displaying-september-13-1425099/
Table of Contents
Overview
A series of short examples on how to convert SQL Server dates to and from JavaScript dates.
Prerequisites
The Moment.js library is used to parse, validate, and format date/time in JavaScript. Click here for more information about Moment.js.
npm install moment
JavaScript Date to SQL Server Date
First import Moment.
import moment from 'moment';
Using Moment() with the Format() property the date is transformed from
const startDate = moment(searchStartDate).format('YYYY-MM-DD');
Output: 2022-04-29
JavaScript: Fri Apr 29 2022 08:54:06 GMT-0700 (Pacific Daylight Time)
To
SQL Server: 2022-04-29 or 2022-04-29 13:00:00
const startDate = moment(searchStartDate).format('YYYY-MM-DD');
Output: 2022-04-29
Date and Time Format
The source code for the entire component.
const sqlDateTime = moment(data.arrivalDate).format('YYYY-MM-DD') + ' ' + moment(data.arrivalDate).format('HH:mm:ss')
Output: 2022-04-29 13:00:00

SQL Server Date to JavaScript Date
Use Moment() to convert a SQL Server date to a JavaScript date.
Goal here is to convert 05-12-2022 to Thu May 12 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
Example with Date and Time
var momentDate=new moment('2022-04-22T20:13:00.000Z');
Output:

Date without Time.
var momentDate=new moment('2022-05-22').format('llll');
Output: Thu, May 12, 2022 12:00 AM
To get the time zone (Pacific Daylight Time), use new Date()
new Date(momentDate.format('llll'))
OR
new Date(new moment('2022-05-22').format('llll');
Output: Thu Sep 22 2022 13:56:56 GMT-0700 (Pacific Daylight Time)
Output of momentDate
Moment {_isAMomentObject: true, _i: '2022-01-03T20:13:00.000Z', _f: 'YYYY-MM-DDTHH:mm:ss.SSSSZ', _tzm: 0, _isUTC: false, …}
_d: Mon Jan 03 2022 12:13:00 GMT-0800 (Pacific Standard Time) {}
_f: "YYYY-MM-DDTHH:mm:ss.SSSSZ"
_i: "2022-01-03T20:13:00.000Z"
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: 'Invalid date', _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …}
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -1, charsLeftOver: 0, …}
_tzm: 0
[[Prototype]]: Object
Once moment has converted the date, any format option is available.
var formattedDate = momentDate.format('MM/DD/YYYY')
Create JavaScript Date With Static Hours
Using setHours() the add a static time to a date in JavaScript.
var today=new Date()
var jsDate = new Date(today.setHours(12,30,0,0))
Output Fri Apr 22 2022 12:30:00 GMT-0700 (Pacific Daylight Time)
You must be logged in to post a comment.