Vue.js Date Format

by J. Albert Bowden

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<div>
  <input type="text" class="form-control" v-model="date">
</div>

<button type="button" @click="getDataFromServer()">
  Get Data
</button>

<button type="button" @click="saveDataToServer()">
  Send Data
</button>

CSS

div {
  margin-bottom: 20px;
}
input {
  padding: 5px 10px; font-size:16px;
}
button {
  padding: 10px 20px; border-radius:0;
}

JavaScript

new Vue({
        el: 'body',
        data: {
          date: null,
        },
        methods: {
        	getDataFromServer: function() {
        		  	//ajaxCall to get data from server
      
        		  	//let's pretend the received date data was saved in a variable (serverDate)
        		  	//let's hardcode for this ex.
        		  	var serverDate = '2015-06-26';
      
        		  	//format it and save to vue data property
        		  	this.date = this.frontEndDateFormat(serverDate);
        	},
        	saveDataToServer: function() {
        		//format data first before sending it back to server
        		var serverDate = this.backEndDateFormat(this.date);
      
        		//ajax call sending formatted data (serverDate)
            
            //will output an alert for this ex.
            alert(serverDate);
        	},
        	frontEndDateFormat: function(date) {
        		return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY');
        	},
        	backEndDateFormat: function(date) {
        		return moment(date, 'DD/MM/YYYY').format('YYYY-MM-DD');
        	}
        }
 });