20

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;
    })
  }
}
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
  • You can just [*reformat the string*](https://stackoverflow.com/questions/39856462/javascript-convert-string-with-full-month-to-date-object/39870230#39870230). – RobG Oct 12 '17 at 11:52

9 Answers9

45

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 }}
Vladimir Salguero
  • 5,609
  • 3
  • 42
  • 47
  • anyone make sure you read moment string format its different i was using django – Fathy Nov 25 '20 at 10:51
  • 1
    When this answer was posted, Vue 3 had only come out a few months prior (Sep, I believe). So this answer is correct for Vue 2. However, filters are depreciated in Vue 3, and methods should be used (as answered below). – Quin Sep 16 '22 at 12:39
  • {{ formDate(response.create_at) }} – elyte5star May 12 '23 at 23:38
26

You can do this easily:

  import moment from 'moment'

  methods: { 
      format_date(value){
         if (value) {
           return moment(String(value)).format('YYYYMMDD')
          }
      },
   },

Then:

format_date(date)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Since Vue 3, filters have be depreciated, and now this is the correct way (although filters can be used). – Quin Sep 16 '22 at 12:40
5

Another good option is to use moment.js lib to format the date, you should install it first in your project through npm npm i --save moment (or see more options on official website) and then you only would have to import it in your component and change the date to the desired format:

import moment from 'moment'
const formattedDate = moment('19 Oct 2017').format('YYYYMMDD')
console.log(formattedDate) //20171019
ricardoorellana
  • 2,270
  • 21
  • 35
4

You can do it by creating new Date object using your string.

var date = new Date("19 Oct 2017");

var result = "" + date.getFullYear() + ((date.getMonth() + 1) > 9 ? '' : '0') + (date.getMonth() + 1) + (date.getDate() > 9 ? '' : '0') + date.getDate();

console.log(result)
Walk
  • 737
  • 4
  • 15
  • 1
    Using the built-in parser is not recommended, especially for non–standard date formats. – RobG Oct 12 '17 at 11:40
  • @RobG so date parsing is not based on some standard and can produce different results in different browsers? I didn't know that! – Walk Oct 12 '17 at 12:12
3

You can break up the string in much the same way a parser would, but avoid creating a date, then format the parts. That will avoid the vagaries of the built-in Date parser:

function reformatDate(s) {
  function z(n){return ('0'+n).slice(-2)}
  var months = [,'jan','feb','mar','apr','may','jun',
                 'jul','aug','sep','oct','nov','dec'];
  var b = s.toLowerCase().split(' ');
  return b[2] + z(months.indexOf(b[1])) + z(b[0]);
}

console.log(reformatDate('19 Oct 2017'));
console.log(reformatDate('1 Jan 2017'));
RobG
  • 142,382
  • 31
  • 172
  • 209
0

TL;DR

new Date('19 Oct 2017').toISOString().substr(0,10).replace(/-/g, '') // returns '20171018'

See the MDN Date and String docs

Explainer:

// Get Date Object
const dateObject = new Date('19 Oct 2017').toISOString()
// Get the Year, month, day substring 
const rawDateString = dateObject.substr(0,10)
// Remove the hyphens
rawDateString.replace(/-/g, '') // returns '20171018'

For hacky, extra formatting you could split the date string by hyphen. Arranging the date as you wish:

let h = new Date('19 Oct 2017').toISOString().substr(0,10).split(/-/)
new Array(h[1], h[0], h[2]).join('-') // returns '10-2017-18'
rujmah
  • 2,267
  • 1
  • 15
  • 13
0

You can use es6 Destructuring and toLocalDateString for a local time that can be followed like this :

const twoDigit = (digit) => digit > 9 ? digit : "0" + digit
const [month, day, year] = new Date().toLocaleDateString().split("\/")
  .map(e => twoDigit(e));
console.log(year + month + day);

Note: You can also use new Date().toLocaleTimeString().substring(0,8).split(":") to get the time component in an array

tuhin47
  • 5,172
  • 4
  • 19
  • 29
0

I came up with this code in vue js and You can use this way

var first_time = '09:00:00'
var today = new Date()
var now_time = (today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()).toString()

if (now_time === first_time){
console.log('true')
}else(){
console.log('false')
}
shoja
  • 103
  • 2
  • 7
0

I rather use pure Javascript function to format date in Vue.js

YourComponent.vue

<template>
  <div>{{ dateFormat(post.date_posted) }}</div>
</template>

<script>
export default {
 methods: {
    dateFormat(v) {
      return (v) => {
        let format = (d) =>
          d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/, "$2 $1, $3");
        return format(new Date(v));
      };
    },
  },
}
</script>
Amit Kumar Khare
  • 565
  • 6
  • 17
Kodediego
  • 21
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 13 '22 at 20:42