5

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"
/>

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

0

The better way to do store the value in a variable and then using datepipe transform covert it into desired format

this.StopDate= this.MachineryForm.controls.StoppageDate.value

this.StopDate = this.datepipe.transform(this.StopDate, 'yyyy-MM-dd');

Comments

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.