Angular2 – typeScript – IsoDate to Html Date

If you want to use <input type “date” .. in Angular2, you need to use theses functions to transform ISO date to HTML date:

 

 

    HTMLDatetoIsoDate(htmlDate){
      let year = Number(htmlDate.toString().substring(0, 4))
      let month = Number(htmlDate.toString().substring(5, 7))
      let day = Number(htmlDate.toString().substring(8, 10))
      return new Date(year, month - 1, day)
    }
    isoDateToHtmlDate(isoDate){
      let date = new Date(isoDate);
      let dtString = ''
      let monthString = ''
      if (date.getDate() < 10) {
        dtString = '0' + date.getDate();
      } else {
        dtString = String(date.getDate())
      }
      if (date.getMonth()+1 < 10) {
        monthString = '0' + Number(date.getMonth()+1);
      } else {
        monthString = String(date.getMonth()+1);
      }
      return date.getFullYear()+'-' + monthString + '-'+dtString
    }

You need to have 2 variables:
datePaiementString and datePaiement

then you have to change format date when you retrieve data from server:

    this.paiementQuoteService.getPaiementQuote(id, {})
      .subscribe(
        res => {
          this.fetchedPaiementQuote = res
          this.fetchedPaiementQuote.datePaiementString = this.authService.isoDateToHtmlDate(this.fetchedPaiementQuote.datePaiement)
        },
        error => {
          console.log(error);
        }
      )

and when you save:

save() {
    this.fetchedPaiementQuote.datePaiement = this.authService.HTMLDatetoIsoDate(this.fetchedPaiementQuote.datePaiementString)
...

in your angular template:

<

        input type="date" class="form-control" [ngModelOptions]="{standalone: true}" class="form-control" [(ngModel)]="fetchedPaiementQuote.datePaiementString" 

>

Bonjour tout le monde !

Bienvenue sur Les sites de GooPlus. Vous lisez votre premier article. Modifiez-le ou supprimez-le, puis commencez à publier !