简体   繁体   中英

Convert date format in Javascript using VueJS

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

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

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)

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

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)

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

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'

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM