5

I am using Angular-7 for web portal application. I have a Material Datepicker from which I would like to only get date with no timestamp. Also it should be in this format: dd/mm/yyyy

This is how it appears on the frontend:

datepicker

<div class="col-xs-6">
  <label for="loading_date">Loading Date</label>
  <div class="input-group date">
    <mat-form-field>
      <input matInput [matDatepicker] = "picker" placeholder = "Choose a date" name="loading_date" [(ngModel)]="quoteModel.loading_date" #loading_date="ngModel" [ngClass]="{'is-invalid' : loading_date.invalid && ((loading_date.dirty || loading_date.touched) || quoteform.submitted)}"   required>
     <mat-datepicker-toggle matSuffix [for] = "picker"></mat-datepicker-toggle>
     <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
  <div class="form-feedback" *ngIf="loading_date.invalid && ((loading_date.dirty || loading_date.touched) || quoteform.submitted)">
  <div style="color:red;" *ngIf="loading_date.errors?.required"class="alert alert-danger">Loading Date is required.</div>
  </div>
  </div>
</div>

I When I submit into the database, I want to get a result in this format:

2019-09-26

But this is what I am getting:

2019-09-26T23:00:00.000Z

How do I achieve this?

1 Answer 1

6

You can use moment to acheive thi;

npm i moment --save

Try this

var dateToDB = moment(loading_date).format("YYYY-MM-DD");

Or you can use DatePipe

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    var dateToDBthis.datePipe.transform(date, 'yyyy-MM-dd'); 
  }
}

In your app.module.ts

providers: [DatePipe,...] 
Sign up to request clarification or add additional context in comments.

3 Comments

Please be aware that moment.js in not recommended for new projects see moment.js project status for more information.
@Tom Angular Material recommends the use of moment and its adapter to use datepicker with locals
Angular material recommends the use of luxon and its adapter to use datepicker with locals

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.