Reputation: 101
I wanted to make a function where user can only claim coins once per day.
I did the function .split
so that it compares the date only since Date()
only compares both date and time. However, i got this javascript error:
Uncaught TypeError (intermediate value).split is not a function
Anyone knows on how to solve this problem? I've tried so many ways. The error is still there.
Here's my code:
$(document).ready(function () {
if (new Date(model[0].lastClaimedDate).split(' ')[0] < new Date().split(' ')[0]) {
document.getElementById('btnAddCoins').disabled = false;
}
else {
document.getElementById('btnAddCoins').disabled = true;
}
})
Upvotes: 4
Views: 63598
Reputation: 1
Instead of using split, you can try to use the spread operator. e.g. arr.split('') could be [...arr]
Upvotes: 0
Reputation: 9135
ISSUE
var date = new Date();
var claimedDate = new Date(date.setDate(date.getDate()-1)) ;
var todaysDate = new Date()
// converting toString and splitting up
claimedDate = claimedDate.toDateString().split(" ");
todaysDate = new Date().toDateString().split(" ");
// result date with array of Day, MonthName, Date and Year
console.log("claimed date", claimedDate)
console.log("todays date", todaysDate)
`var d = new Date();` // Todays date
if you do a d.split(" ")
:: gives you an error d.split is not a function
you can split it by d.toDateString().split(" ")
// gives you an array of ["Fri", "Sep", "28", "2018"]`
using the above you can check with the previous date
you can check the toDateString method, now the array consist of Day, month, date, and year. So you can check the previous date and you can disable or enable the button.
BETTER SOLUTION
No need to convert it toString and split , you can direclty check the two dates directly, check the solution
SOLUTION
$(document).ready(function () {
var date = new Date();
var lastClaimedDate = new Date(date.setDate(date.getDate() - 1 ));
var currentDate = new Date();
if(lastClaimedDate < currentDate){
$("#btnAddCoins").prop("disabled", true)
}else{
$("#btnAddCoins").prop("disabled", false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAddCoins">Add Coins</button>
Upvotes: 8
Reputation: 1337
You can coerce your date into a string and then split on it:
let strDate = (''+new Date()).split(' ')[0]
console.log( strDate )
This is the wrong solution for your problem, though. Consider comparing the date object and not the strings.
let strLastClaimedDate = '01/02/2017 01:30:00'
let dtLastClaimedDate = new Date(strLastClaimedDate)
console.log(formatDate(dtLastClaimedDate))
if ( formatDate(dtLastClaimedDate) < formatDate(new Date('01/02/2017 02:00:00')) )
console.log('date is older')
else
console.log('same day (or after)')
function formatDate(dt){
let month = dt.getMonth()+1
month = month < 10 ? '0'+month : month
let day = dt.getDate()
day = day < 10 ? '0'+day : day
return [dt.getFullYear(),month,day].join('')
}
Upvotes: 0