Home > database >  VUEJS - How to Convert Date from API Response
VUEJS - How to Convert Date from API Response

Time:04-21

I'm doing my project with API and the default birthdate from the response is YYYY-MM-DD but I wanna format and show the birthdate in my modal dialog in this format DD-MM-YYYY,

enter image description here

here's the code

axios
.post("test/test).
.then((response) => {
          if (response.data.patients.length === 0) {
            this.showAlert(this.$t("tess"), "error");
          } else {
            this.dataLoad = response.data.patients[0].patient;
            console.log(this.dataLoad);
          }
}) 

I save the response in dataLoad and wanna show the format DD-MM-YYYY in modal dialog

<v-row>
            <v-col cols="4">Birthdate</v-col>
            <v-col cols="1">:</v-col>
            <v-col cols="7">{{
              this.dataLoad && this.dataLoad.birthdate
            }}</v-col>
</v-row>

CodePudding user response:

Call the following function.

function formatDate(dateStr)
{
    var parts = dateStr.split("-"); 
    return parts[2]  "-"   parts[1]  "-"   parts[0];
}

Alternatively, you can use it as follows.

<v-row>
        <v-col cols="4">Birthdate</v-col>
        <v-col cols="1">:</v-col>
        <v-col cols="7">{{
          this.dataLoad && this.dataLoad.birthdate.split("-").reverse().join("-")
        }}</v-col>
</v-row>

CodePudding user response:

you can first of all prepare the birth Date like the format you want after that you can load it to your component:

    new Vue({
      el: '#vueRoot',
      data: {birthDate: '1963-11-22'},
      computed:{
        birthDateDdmm(){
          return new Date(this.birthDate   'T00:00:00Z')
          .toLocaleDateString('en-GB',{timeZone:'UTC'})
        },
        birthDateAuto(){
          return new Date(this.birthDate   'T00:00:00Z')
          .toLocaleDateString([],{timeZone:'UTC'})
        }
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id='vueRoot'>
      <h1>input => {{birthDate}}</h1>
      <h1>dd-MM-yy => {{birthDateDdmm}}</h1>
      <h1>respect user prefs => {{birthDateAuto}}</h1>
</div>

  • Related