Skip to content

How to sort Vuetify date range picker?

I have a vuetify date range picker as shown:

                    <v-menu ref="effectiveDateMenu"
                        v-model="effectiveDateMenu"
                        :close-on-content-click="false"
                        transition="scale-transition"
                        offset-y
                        max-width="290px"
                        min-width="auto">
                    <template v-slot:activator="{ on, attrs }">
                        <v-text-field label="Time Period"
                                      v-model="effectiveDateRange"
                                      filled
                                      dense
                                      rounded
                                      @*:rules="[v => !!(v && v.length) || 'Rating period is required']"*@
                                      v-bind="attrs"
                                      v-on="on"
                                      range
                                      required
                                      :class="toggleEdit ? 'locked' : 'editable'"
                                      :readonly="toggleEdit"></v-text-field>
                    </template>
                    <v-date-picker v-model="dates"
                                   no-title
                                   @@input="datesPicked()"
                                   range></v-date-picker>
                </v-menu>

Then use the following computed property to return the values to the text field however I cannot get the dates to be in order. You can only choose two dates and if you choose the newer date first it fills in the text field with that value first even if I use the sort function on the v-model for the date picker. Any help would be appreciated.

            computed: {
            effectiveDateRange: function () {
                // `this` points to the vm instance

                return this.dates.map((element) => {
                    var d = new Date(element);
                    return `${d.getUTCMonth() + 1}/${d.getUTCDate()}/${d.getUTCFullYear()}`;
                }).sort(function (a, b) {
                    // Turn your strings into dates, and then subtract them
                    // to get a value that is either negative, positive, or zero.
                    return new Date(b.date) - new Date(a.date);
                }).join(' - ')
            }
        }

Answer

Since the elements of the dates array are strings in the ISO 8601 format (YYYY-mm-dd or YYYY-mm), in which date and time values are in order from most significant to least significant, you can simply sort the array:

effectiveDateRange: function() {
  return this.dates.sort().join(' - ');
}