I'm attempting to display how much time is left, based on a mysql timestamp. For some reason the output is -1 days, 23 hours, 59 minutes, 59 seconds.
<script type="text/javascript">
function update(datetime = "2021-07-15 20:24:42") {
timeleft = new Date(datetime);
now = new Date();
secs = (timeleft - now) / 1000;
days = Math.floor(secs / (3600 * 24));
hours = Math.floor((secs - (days * (3600 * 24)))/3600);
minutes = Math.floor((secs - (days * (3600 * 24)) - (hours * 3600)) / 60);
seconds = Math.floor(secs - (days * (3600 * 24)) - (hours * 3600) - (minutes * 60));
if (seconds < 0) {
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
}
return days+' days, '+ hours+' hours, '+minutes+' minutes, '+seconds+' seconds';
}
// time is pulled from database, but plugged in manually
member = Date("06-08-21 16:06:37");
alert("Left: "+update(member));
</script>
Any info would be appreciated
1) You can use new Date() to create a new instance and pass a valid date.
2) You are using dd-mm-yy format so you should make it valid because if you pass it directly then it will convert the date
member = new Date(dateString); // 2021-06-08T10:36:37.000Z
i.e Date is 08, month = 06, So you have to swap the date and month value before getting the date instance from new Date()
const dateString = "06-08-21 16:06:37".replace(
/(\d\d)-(\d\d)-(\d\d \d\d:\d\d:\d\d)/,
`$2-$1-$3`
);
function update(datetime = "2021-07-15 20:24:42") {
timeleft = new Date(datetime);
now = new Date();
secs = (timeleft - now) / 1000;
days = Math.floor(secs / (3600 * 24));
hours = Math.floor((secs - days * (3600 * 24)) / 3600);
minutes = Math.floor((secs - days * (3600 * 24) - hours * 3600) / 60);
seconds = Math.floor(secs - days * (3600 * 24) - hours * 3600 - minutes * 60);
if (seconds < 0) {
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
}
return (
days +
" days, " +
hours +
" hours, " +
minutes +
" minutes, " +
seconds +
" seconds"
);
}
// time is pulled from database, but plugged in manually
const dateString = "06-08-21 16:06:37".replace(
/(\d\d)-(\d\d)-(\d\d \d\d:\d\d:\d\d)/,
`$2-$1-$3`
);
member = new Date(dateString);
console.log("Left: " + update(member));
Related
Goal: Once the time hits two days or less, then it switches to hours instead of days.
Problem: In checking code by changing the date, it still only shows the days left, and not the hours. Am I missing something?
var countDownDate = new Date("Nov 15, 2020 11:59:59").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
if (distance < 2) {
clearInterval(x);
document.getElementById("aep-countdown-date").innerHTML = hours + " hours left";
}
else if (distance < 0) {
clearInterval(x);
document.getElementById("aep-countdown-date").innerHTML = "The time has ended.";
}
else {
clearInterval(x);
document.getElementById("aep-countdown-date").innerHTML = days + " days left";
}
});
The Date method getTime returns:
the number of milliseconds* since the Unix Epoch.
Your code countDownDate - now returns the number of milliseconds from now until the target date.
However, your comparison distance < 2 is treating distance (which is in ms) as if it were in days.
You probably want
ms in seconds ------------------+
seconds in hour ---------+ |
hours in day ------+ | |
days -+ | | |
| | | |
if (distance < 2 * 24 * 3600 * 1000) {
/* ... */
}
With help of the previous two responses, I figured it out. I added "2x" to the hours variable and changed the variable to days in the if statements and rid of the setInterval because it wasn't needed (I only need days and hours, not milliseconds and for it to constantly be firing):
var countDownDate = new Date("Nov 15, 2020 11:59:59").getTime();
$(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor(
(2 * (distance % (1000 * 60 * 60 * 24))) / (1000 * 60 * 60)
);
document.getElementById("aep-countdown-date").innerHTML =
days + " days left.";
if (days < 0) {
document.getElementById("aep-countdown-date").innerHTML = "Time has ended.";
}
if (days < 2) {
document.getElementById("aep-countdown-date").innerHTML =
hours + " hours left.";
}
});
how do I get, for example, the date of next monday and the time 5:30PM, and calculate the difference between current date and time and that date and time?
if I run it now at 8/28/2020 17:35, it should give me 8/31/2020 17:30 and the difference 2 days 23 hours 55 minutes.
I hope this help:
// takes dayIndex from Sunday(0) to Saturday(6)
const getNextDay = (dayIndex) => {
const today = new Date();
today.setDate(
today.getDate() + ((dayIndex - 1 - today.getDay() + 7) % 7) + 1
);
today.setHours(17, 30, 00);
return today;
};
const getTimeleft = (dateNow, dateFuture) => {
let seconds = Math.floor((dateFuture - dateNow) / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
let days = Math.floor(hours / 24);
hours = hours - days * 24;
minutes = minutes - days * 24 * 60 - hours * 60;
seconds = seconds - days * 24 * 60 * 60 - hours * 60 * 60 - minutes * 60;
return `${days} days ${hours} hours ${minutes} minutes`;
};
const now = new Date();
const nextMonday = getNextDay(1);
const timeleft = getTimeleft(now, nextMonday);
console.log(nextMonday.toLocaleString());
console.log(timeleft);
You could use moment.js, it's a very useful library when it comes to dates:
<script src="https://momentjs.com/downloads/moment.js"></script>
<script>
const today = moment();
const nextMonday = moment().add(1, 'weeks').isoWeekday(1);
nextMonday.set({'hour': 17, 'minute': 30, 'seconds': 0});
console.log(nextMonday.toString());
const duration = moment.duration(nextMonday.diff(today));
const days = duration.asDays();
const hours = (days - Math.floor(days)) * 24;
const minutes = (hours - Math.floor(hours)) * 60;
console.log("days", Math.floor(days));
console.log("hours", Math.floor(hours));
console.log("minutes", Math.floor(minutes));
</script>
Here is the working example:
function nextWeekMonday(date)
{
var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
var currWeekMonday = new Date(date.setDate(diff));
return new Date(currWeekMonday.getTime() + 7 * 24 * 60 * 60 * 1000);
}
function getDateDifference(current, future) {
// get total seconds between the times
var delta = Math.abs(future - current) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60;
return `${days} Days, ${hours} Hours, ${minutes} Minutes, ${seconds} Seconds`;
}
var curr = new Date; // get current date
var nextMonday = nextWeekMonday(curr);
console.log(getDateDifference(curr, nextMonday));
I just want to know how to make countdown after 0 0 0 0 its directly back to 23:59:59 so i have a problem when i try to create countdown function when its expired it will go to -0d -0h -0m -1s , -0d -0h -0m -2s but when i refresh it back to 23.59.58 , 23,59,57. i just want to know after clear interval it direcy go to 23.59.59 not -0d -0h -0m -0s . this is my script
countdown.js
function warTime2(countDownDate) {
var countDownDate = new Date();
countDownDate.setHours(14);
countDownDate.setMinutes(0);
countDownDate.setSeconds(0);
var now = new Date();
if (now.getHours() < countDownDate.getHours()) {
countDownDate = countDownDate;
} else if (countDownDate.getHours() <= now.getHours()) {
countDownDate.setDate(countDownDate.getDate() + 1);
}
var x = setInterval(function () {
var now = new Date();
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(
(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
document.getElementById("second_chip_war").innerHTML =
"02:00 PM War Start in " + hours + ":" + minutes + ":" + seconds;
if (distance < 0) {
clearInterval(x);
let newDate = countDownDate + 8 * 3600 * 1000;
warTime2(newDate);
}
}, 1000);
}
Thank you, glad to hear if you want to help me
You need to check whether distance is less than 0 when you first assign it, and if so, increase countDownDate by a day before recomputing distance and continuing the function:
function warTime2(countDownDate) {
var countDownDate = new Date();
countDownDate.setHours(14);
countDownDate.setMinutes(0);
countDownDate.setSeconds(0);
var now = new Date();
if (now.getHours() < countDownDate.getHours()) {
countDownDate = countDownDate;
} else
if (countDownDate.getHours() <= now.getHours()) {
countDownDate.setDate(countDownDate.getDate() + 1);
}
var x = setInterval(function() {
var now = new Date();
var distance = countDownDate - now;
if (distance < 0) {
// countdown complete, add a day to countDownDate and restart
countDownDate.setDate(countDownDate.getDate() + 1);
distance = countDownDate - now;
}
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
document.getElementById("second_chip_war").innerHTML = "02:00 PM War Start in " + hours + ":" +
minutes + ":" + seconds;
}, 1000);
}
warTime2('2020-06-21');
<div id="second_chip_war"></div>
How can I set a GMT to date.Now()?
var countDownDate = getNextDayOfWeek(new Date(),0,21);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24)).toString();
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString();
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)).toString();
var seconds = Math.floor((distance % (1000 * 60)) / 1000).toString();
// Add 0 when value are < 10
hours = (hours < 10) ? "0"+hours : hours;
minutes = (minutes < 10) ? "0"+minutes : minutes;
seconds = (seconds < 10) ? "0"+seconds : seconds;
var grb = jq("#grb");
// Display the result in the element with id="grb"
grb.html(days + "d " + hours + "h " + minutes + "m " + seconds + "s");
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
var one_hour = -60 * -60 * -1000;
if(distance < one_hour){
grb.html("GRB is finished!");
}else{
grb.html("GRB is open!");
}
}
}, 1000);
});
It keeps using the time of your computer, and I want to use a timezone to be stored everytime.
I have tried TimeZoneOffset, didn't worked, any help would be appreciated.
please see this
var now = new Date();
var nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var distance = end - nowUTC;
So i was looking for a function to get the timespan between two dates and i've found this answer on SO
Work with a time span in Javascript
However the date is in this format 7/Nov/2012 20:30:00 and my dates are 7/11/2012 20:30:00, and my values came from inputs
http://jsbin.com/igaruj/47/edit
If a try to change "Nov" to "11" i got NaN on the output. Do i have to convert the dates ?
Here is the code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
</head>
<body>
<input type="text" id ="start"value="7/Nov/2012 20:30:00" />
<input type="text" id="end" value="20/Nov/2012 19:15:00" />
</body>
</html>
The javascript
var startDate = document.getElementById("start").value;
var endDate = document.getElementById("end").value;
var date1 = new Date(startDate);
var date2 = new Date(endDate);
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
With your 20/11/2012 20:30:00 date format:
var startDate = "7/11/2012 20:30:00";
var endDate = "20/11/2012 19:15:00";
You're getting the NaN because, it wants it in the format mm/dd/yyyy. So 20 is ofcourse an invalid month.. interchange the month and day values like:
var parts = startDate.split('/');
startDate = parts[1] + '/' + parts[0] + '/' + parts[2];
// 11/7/2012 20:30:00
var parts = endDate.split('/');
endDate = parts[1] + '/' + parts[0] + '/' + parts[2];
// 11/20/2012 9:15:00
and then do your normal time diff work and it will work:
var date1 = new Date(startDate);
var date2 = new Date(endDate);
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
alert(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
//12 days 22 hours 45 minutes 0 seconds
See the DEMO here
Use JavaScript's Date and simply call new Date("7/Nov/2012 20:30:00") to get a JS Date object. Then you could extract the day, month and year using methods on that Date object.