Angular – Convert Date to SQL Server Date Format

Table of Contents
Overview
Using Angular Material’s Date Pick or generating date from Typescript, the date looks like the following:
Wed Jun 17 2020 09:05:29 GMT-0700 (Pacific Daylight Time)
In order to use it against a date time in SQL Server, the date needs to be formatted to YYYY-MM-DD HH:MM:SS
Solution
First go to your root module apps.module.ts and add the following.
import { DatePipe } from '@angular/common'
Add the DatePipe as a provider.
providers: [DatePipe]
From the component.
Import DatePipe in your component.ts file.
import { DatePipe } from '@angular/common';
In your components constructor:
constructor(public datepipe: DatePipe) { }
Converting the date.
date = new Date();
onSubmit() {
const formatDate = this.datepipe.transform(this.date, 'yyyy-MM-dd');
console.log(formatDate);
}
Formatted – Result
Your should see the following output in the console window.
2020-06-17
Angular Material Date Range Example
Date Range HTML
<mat-form-field appearance="outline">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [formGroup]="range" [rangePicker]="picker">
<input matStartDate formControlName="start" placeholder="Start date">
<input matEndDate formControlName="end" placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
Typescript Create the Date Range FormGroup
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { DatePipe } from '@angular/common';
Define range with FormGroup. FormGroup and DatePipe in the Constructor
public range = new FormGroup({
start: new FormControl(),
end: new FormControl()
});
constructor( private fb: FormBuilder,
private datepipe: DatePipe) { }
Call a service to get the record start and end dates.
this.subs.add(this.eventAdminSVC.getSingleEvent(eventId).subscribe((data) => {
const sDate = this.datepipe.transform(data.StartDate, 'yyyy-MM-dd');
const eDate = this.datepipe.transform(data.EndDate, 'yyyy-MM-dd');
// Put the new dates in the date range control
this.range.controls.start.setValue(sDate);
this.range.controls.end.setValue(eDate);
},
(err: HttpErrorResponse) => {
console.log(err);
}));
Date Range with formatted default values

You must be logged in to post a comment.