Convert date format in Javascript using VueJS

user6189981 picture user6189981 · Oct 12, 2017 · Viewed 56k times · Source

I have a date format of 19 Oct 2017 and want to convert it to this format 20171019

Is there a quick way of doing this? I am using FlatPickr in VueJs. Please find my code below if its any help.

import flatPickr from 'vue-flatpickr-component';
import 'flatpickr/dist/flatpickr.css';
import Navigation from './Navigation'
import bus from '../bus'
export default {
  data() {
    return {
      showPanel: false,
      isClosed: false,
      arrival: null,
      departure: null,
      config: {
        dateFormat: "Ymd"
      }
    }
  },
  components: {
    flatPickr
  },
  methods: {
    closeMenu: function() {
      this.$store.state.showBooking = false;
    }
  },
  mounted() {
    bus.$on('show-booking', () => {
      this.showPanel = true;
    })
  }
}

Answer

Vladimir Salguero picture Vladimir Salguero · Mar 13, 2020

Use moment

First we need to install moment npm package that will allow to change date format.

npm install moment

Now you can create a global function to set the format you want, to do so you must open the file resources/js/app.js and put the following code:

import moment from 'moment';

Vue.filter('formatDate', function(value) {
    if (value) {
        return moment(String(value)).format('MM/DD/YYYY hh:mm')
    }
});

Now in all your js components you can apply the format as follows:

{{ response.create_at | formatDate }}