1

I am trying to convert a string to Date, but I am getting a Invalid Date error.

The input would be a String containing one of the following data formats:

  • YYYY only year
  • MM/YYYY month & year
  • DD/MM/YYYY full date

The expected output is a Date type, however, the only format I cannot convert is MM/YYYY one.

How could I solve this specific case? Thanks.

ShellNinja
  • 629
  • 8
  • 25
Caike Motta
  • 193
  • 3
  • 16
  • 2
    You could read up on [Javascript date parsing](https://stackoverflow.com/questions/5619202/converting-string-to-date-in-js), or look at a library such as [moment.js](https://momentjs.com/) – Matthew Hegarty May 03 '18 at 20:04

1 Answers1

0

I solved it using the following code:

@Input() initialDate: any; //Either "YYYY", "MM/YYYY" or "DD/MM/YYYY"
@Input() mask: string = 'text' //Either "full", "month" or "year";

ngOnInit() {
  // Handle initialDate value
  this.setInitialDate();
}

private setInitialDate() {
  if (this.initialDate) {
    switch (this.mask) {
      case 'full':
        this.day = this.initialDate.getDate().toString();
        this.month = this.months[this.initialDate.getMonth()];
       this.year = this.initialDate.getFullYear().toString();  

      break;
    case 'month': 
      let monthYear = this.initialDate.split('/');
      if (monthYear.length == 2) {
        this.month = this.months[monthYear[0] - 1];
        this.year = monthYear[1];
      }

      break;
    case 'year': 
      this.year = this.initialDate;

      break;
    default:
      break;
    }
  }
}
Caike Motta
  • 193
  • 3
  • 16