Im trying yo compare two dates, 1 is the date today second is the date based in my database(SQL Query). They told me to use new Date()
but I'm confused how can I insert php variable
there. So here's my code:
<script type="text/javascript">
var today = new Date();
var expired = new Date(today);
function myDIV() {
if (today >= expired) {
document.getElementById("myDiv").style.backgroundColor="#ff4d4d";
}
}
</script>
What I'm trying to do is whenever the second date is the same date as today, the div will change it's color. So I've tried using >=
and ==
but no luck. Also I tried to do this:
<script type="text/javascript">
var today = new Date();
var expired = new Date($passport_expiration);
function myDIV() {
if (today.getTime() >= expired.getTime()) {
document.getElementById("myDiv").style.backgroundColor="#ff4d4d";
}
}
</script>
The format of the date is mm/dd/Y
<script type="text/javascript">
var today = new Date();
var expired = new Date("<?php echo $passport_expiration; ?> ");
alert(expired);
function myDIV() {
if (today.getTime() >= expired.getTime()) {
document.getElementById("myDiv").style.backgroundColor="#ff4d4d";
}
}
</script>
<?php
#$passport_expiration = "07/12/2016";
$passport_expiration = "07/18/2016";
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
var today = new Date();
var expired = new Date("<?php echo $passport_expiration; ?> ");
alert(today.getTime() >= expired.getTime());
</script>
</body>
</html>
Oh dates are fun! There's a few things to think about.
getTime()
from JavaScript you're getting the number of milliseconds since 1970, so any date today won't equal your date from PHP which will convert to the time at midnight. var testDate = '7/16/16'; var today = new Date(); var month = today.getMonth() + 1; var day = today.getDate(); var fullYear = today.getFullYear() - 2000; var todayString = month + '/' + day + '/' + fullYear; console.log(todayString); console.log(testDate); console.log(todayString === testDate);
If it's all a bit daunting and you'll need to be working with JavaScript dates a lot, check out momentjs (although it's relatively huge if that's a concern).
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.