TypeScript(Angular) Datetime To Date

17,317

Solution 1

The first solution provided is great, as it solves your solution with Vanilla JavaScript!

However, I have two other alternative solutions.

1) This makes use of Angular's built-in DatePipe. You can even pass in a variety of DateTime formats.

import { DatePipe } from '@angular/common';
.
.
export class SampleComponent implements OnInit {   

  constructor(private datePipe: DatePipe) {
    this.addItems.achievement_date = datePipe.transform('2019-04-13T00:00:00', 'yyyy-MM-dd');
    // console.log(this.date)
  }

}

Do remember to import DatePipe to your providers in your module that is using it.

import { DatePipe } from '@angular/common';
.
.
@NgModule({
  .
  .,
  providers: [
    DatePipe
  ]
})

The above should display the dates on the input field. I have made a demo using the above solution

2) formatDate. Do take note that this may not work on the earlier versions of Angular. So far, I have only tried and tested it on Angular 7.

import {formatDate } from '@angular/common';
.
.
export class AppComponent  {

  date = undefined;

  constructor() {
   this.date = formatDate('2019-04-13T00:00:00', 'yyyy-MM-dd', 'en-US');
  }

}

here is another demo for you.

Solution 2

this utility function my help

export const getDate = function (date: any): Date {
  const _date = new Date(date);
  return new Date(
    Date.UTC(_date.getFullYear(), _date.getMonth(), _date.getDate())
  );
};

or another way to return the string value base on format 'yyyy-MM-dd'

export const getDate = function (date: any): string{
  const _date = new Date(date);
  return `${_date.getFullYear()}-${_date.getMonth()}-${_date.getDate()}`;      
};

before you save the date just clean up the value

this.addItems.achievement_date = getDate(this.addItems.achievement_date);
Share:
17,317
Z.Kirik
Author by

Z.Kirik

Updated on June 11, 2022

Comments

  • Z.Kirik
    Z.Kirik almost 2 years

    I got this error message

    The specified value "2019-04-13T00:00:00" does not conform to the required format, "yyyy-MM-dd".

    I want to change the date / time to a date.

    datetime example:2019-04-13T00:00:00

    I want to do example:2019-04-13

    HTML

     <input
      class="form-control mr-sm-2"
      id="dates"
      name="achievement_date"
      [(ngModel)]="addItems.achievement_date"
      required
      type="date"
      placeholder="Tournament Date"
    />