Convert date format in Javascript using VueJS

心不动则不痛 提交于 2019-12-02 16:50:14

问题


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:


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)



回答2:


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



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



回答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)


来源:https://stackoverflow.com/questions/46708110/convert-date-format-in-javascript-using-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!