Use moment to format date in a vue component

Viewed 1863

I have a Vue component with an input field which is a date type:

<input
    type="date"
    name="start_date"
    id="start_date"
    v-model="absence.start_date"
>

In my script I am trying to format the date so that it displays correctly:

<script>
    export default {
        data() {
            return {
                absence: {
                    start_date: null,
                }
            }
        },
        created() {
            const request = axios
                .get(`/api/absences/${this.$route.params.id}`)
                .then(response => {
                    this.absence = response.data.data;
                });
        }
    }
</script>

However it doesn't work with the format returned by the API.

If I set the date manually it works in this format

start_date: '2021-01-01',

However it is overwritten by the api call. I have moment installed in app.js, how can I use moment to format the date returned by the api call?

EDIT

This is the API response:

{"success":true,"data":{"id":1,"start_date":"2021-07-24 00:00:00","end_date":"2021-07-25 00:00:00","notes":"Quis nisi repellendus ipsa. Eum asperiores sunt iusto exercitationem autem. Qui harum adipisci praesentium laboriosam. Fugit quasi voluptatem excepturi et non autem atque quibusdam. Sed aperiam molestias quaerat incidunt.","created_at":"2021-06-28T19:34:16.000000Z","updated_at":"2021-07-03T15:46:10.000000Z","status":1}}
2 Answers

You can do something like the below. Working Sample Code here

And Make sure you install the moment js

<input
   type="date"
   name="start_date"
   id="start_date"
   v-model="formattedStartDate"
>

// Make sure moment is installed

<script>
    import moment from 'moment'

    export default {
        data() {
            return {
                absence: {
                    start_date: null,
                }
            }
        },
        computed: {
            formattedStartDate() {
                return moment(this.absence.start_date).format('yyyy-MM-DD');
            }
        },
        created() {
            const request = axios
                .get(`/api/absences/${this.$route.params.id}`)
                .then(response => {
                    this.absence = response.data.data;
                });
        }
    }
</script>

The <input type="date"> only accepts the date portion of an ISO date string as a valid value, but the API data includes the time:

{
  "start_time": "2021-07-24 00:00:00"
                            ^^^^^^^^
}

You can easily parse the date from that string with String.prototype.split on the space, taking the first array element (the date):

const data = response.data.data
this.absence = {
  ...data,
  start_date: data.start_date.split(' ')[0]
}

demo

Related