1
votes

I am trying to format the input from the Angular material datepicker.

For example when the user types 2,3,2018 and press enter, the date is set to this: 2/3/2018. The problem is, that datepicker take the value in the form of an id, for example for 2/3/2018 it uses the id 1517608800000. I can format the value in the compoment like this using Moment.js like this:

this.value.format('MM/DD/YYYY')

And it formats the code correctly, but it does not apply it back to the input. In the view the value is bound with ngModel.

1
I now how to change the format type, my problem is when the user types in the input for example 2.3.2018 and press enter to set in the input the value like this 2/3/2018 how is the default formatBogdan
why someone would enter a date like 2.3.2018? is a requirement to be like that? you will need to parse every variant of the separatorsPaulo Galdo Sandoval

1 Answers

0
votes

Maybe you could use a pipe:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
   name: 'datex'
})

export class DatexPipe implements PipeTransform {
  transform(value: any, format: string = ''): string {
  // Try and parse the passed value.
  const momentDate = moment(value);

  // If moment didn't understand the value, return it unformatted.
  if (!momentDate.isValid()) {
    return value;
  }

  // Otherwise, return the date formatted as requested.
  return momentDate.format(format);
}
}

And apply it to the template:

  {{data | datex: "DD/MM/YYYY HH:mm:ss"}}