21

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;
    })
  }
}
1

9 Answers 9

50

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 }}
Sign up to request clarification or add additional context in comments.

3 Comments

anyone make sure you read moment string format its different i was using django
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).
{{ formDate(response.create_at) }}
30

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)

1 Comment

Since Vue 3, filters have be depreciated, and now this is the correct way (although filters can be used).
6

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)

2 Comments

Using the built-in parser is not recommended, especially for non–standard date formats.
@RobG so date parsing is not based on some standard and can produce different results in different browsers? I didn't know that!
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

Comments

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'));

Comments

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'

Comments

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

Comments

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')
}

Comments

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>

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.