'How to compare dates in Vuejs?
Hi I'm trying to make a library/book tracking app which tracks the date and returns the status like its returned or lost etc. I need to compare dates in my app but i can't find how to in vuejs could you please help thanks.
<html>
<head>
<meta charset=utf-8>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="newVue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="message" required placeholder="Enter Name">
<input type="date" v-model="enterdate" placeholder="Enter Date">
<table border="1" v-for="item in items">
<tr>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
</tr>
</table>
<button @click="addRow">Add</button>
</div>
</body>
window.addEventListener('load',()=>{
window.vue = new Vue({
el: '#app',
data: {
message:'',
enterdate:'',
items:[{
name:'',
}]
},
methods: {
addRow() {
this.items.push({
name: this.message,
date: this.enterdate,
})
},
}
})
})
Solution 1:[1]
Looks like you have dates represented as strings. Then to compare it you need to parse it first. I would recommend you to take some existing library for this. http://momentjs.com/ is a good example.
Then you would do something like:
dateA = moment(itemA.date, "MM-DD-YYYY"); // replace format by your one
dateB = moment(itemB.date, "MM-DD-YYYY");
if (dateA.diff(dateB) > 0) {
// do something if A is later than B
} else {
// do something if B is later that A
}
Solution 2:[2]
You can simply wrap your date string into new Date()
and compare as follows new Date(this.enterdate) < new Date()
Check the snippet as well.
new Vue({
el: '#app',
data: {
message: '',
enterdate: '',
items: [{
name: '',
}]
},
methods: {
addRow() {
if (new Date(this.enterdate) < new Date()) {
alert("Today or Past date");
} else {
alert("Future date");
}
this.items.push({
name: this.message,
date: this.enterdate,
})
},
}
})
<html>
<head>
<meta charset=utf-8>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="newVue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="message" required placeholder="Enter Name">
<input type="date" v-model="enterdate" placeholder="Enter Date">
<table border="1" v-for="item in items">
<tr>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
</tr>
</table>
<button @click="addRow">Add</button>
</div>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | tuhin47 |