I'm trying to create a counter that shows how much time you've spent on the site and I use sessionStorage to access the Date object from multiple pages.
The problem is that the counter starts at 01:00:00 even though I initialized the Date with 00:00:00.
Here is my code:
function checkTime(){
if(document.getElementById("clock")[13] == ''){
var d = new Date('2010-06-11T00:00:00');
sessionStorage.setItem('time', d);
}
}
function updateTime(){
checkTime();
var nDate = new Date(sessionStorage.getItem('time'));
nDate.setSeconds(nDate.getSeconds() + 1);
sessionStorage.setItem('time', nDate);
var hours = (nDate.getHours()<10 ? "0" : "") + nDate.getHours();
var minutes = (nDate.getMinutes()<10 ? "0" : "") + nDate.getMinutes();
var seconds = (nDate.getSeconds()<10 ? "0" : "") + nDate.getSeconds();
var timeString = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").innerText = timeString;
}
setInterval(updateTime, 1000);
It starts at 01:00 due to your timezone (UTC +1 CET Central European Time, Stockholm).
Create your date in the following manner:
const utcDate = new Date(Date.UTC(2019, 5, 11, 0, 0, 0)); // second param is the month-index, it start at 0, so 5 means june
console.log(utcDate);
Why don't use the unix timestamp, is really more simple and timezone free.
When user enter on the website
var d = new Date().getTime();
sessionStorage.setItem('time', d);
then
function updateTime(){
var nDate = new Date().getTime();
var startDate = sessionStorage.getItem('time');
var duration = nDate-startDate;
var seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
var timeString = hours + ":" + minutes + ":" + seconds;
document.getElementById("clock").innerText = timeString;
}
setInterval(updateTime, 1000);
Related
<script>
window.setInterval(function(){ document.title = "site - " + msToTime();}, 1000);
function msToTime() {
var milliseconds = parseInt((remainingTime % 1000) / 100),
seconds = parseInt((remainingTime / 1000) % 60),
minutes = parseInt((remainingTime / (1000 * 60)) % 60),
hours = parseInt((remainingTime / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
</script>
remainingTime would bring however much seconds left in the timer (00:07:19.7). When I change document.title to alert(), it would successfully give alerts every second, but I want the tab title to update every second. How would I accomplish this?
Here you go! That's what you wanted? I edited your code adding the functionality of time, test it! changing every millisecond.
P.S - If i were you i would delete the milliseconds. Stays more clean without it
window.setInterval(function(){ document.title = "rumseytime - " + msToTime();}, 1000);
function msToTime() {
var remainingTime = new Date();
var milliseconds = remainingTime.getMilliseconds();
seconds = remainingTime.getSeconds();
minutes = remainingTime.getMinutes();
hours = remainingTime.getHours();
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
Key variables to keep in mind:
This is set to simulate 11:00 PM.
var bt = "23:00";
This is set to simulate 8:00 AM.
var wt = "08:00";
The desired functionality:
The countdown timer starts every morning at 8:00 AM.
It counts down until 11:00 PM, every night.
Then it stays at 00:00:00.
In the morning, at 8:00 AM, it repeats the count-down, again.
This should happen forever.
What is actually happening:
Everything is working fine, except it is starting a 24 hour countdown at midnight, until 8:00 AM.
I have tried debugging this, and I suspect the error lies in what is calculated as the distance variable, making the code think that it is comparing against the next day, but I am not sure how to remedy this.
Here is the Codepen.
and here is my JS code:
$(document).ready(function () {
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dateNow = moment().format('MMM D, YYYY');
placeHolderDate = dateNow + " " + bt;
var timeNow = moment().format('HH:mm');
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// 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 and the count down 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);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
var timeNow = moment().format('HH:mm');
//console.log('Time Now:' + timeNow);
//console.log('Wake Time:' + wt);
if (timeNow === wt) {
clearInterval(x);
restartCountdown();
}
//console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
function restartCountdown() {
//log("restartCountdown Started!");
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dN = (moment().add(moment.duration({d: 1})).format('MMM D, YYYY'));
console.log('dn ' + dN);
var placeHolderDate = dN + " " + bt;
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// 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 and the count down 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);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
// console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
}
});
I have edited your code and created this codepen https://codepen.io/anon/pen/aabjEb?editors=0010. Please feel free to optimize the code since I have not done it. The idea was is check if time is between 8 AM and 11 PM. If yes show value else show 00:00:00. Also once the date changes, update the dates and now compute accordingly
$(document).ready(function () {
function countdown() {
var bt = "23:00", // 11:00 PM
wt = "08:00"; // 08:00 AM
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth()+1,
yyyy = today.getFullYear();
var startTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + wt),
endTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + bt);
setInterval(function() {
var now = new Date();
var nowdd = today.getDate();
var nowTime = now.getTime();
if(dd !== nowdd) {
dd = nowdd;
var nowmm = now.getMonth() + 1,
nowyyyy = now.getFullYear();
startTime = new Date(dd + '/' + mm + '/' + yyyy + ' wt');
endTime = new Date(dd + '/' + mm + '/' + yyyy + ' bt');
}
if(nowTime > startTime && nowTime < endTime) {
// Find the distance between now and the count down date
var distance = endTime - nowTime;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
} else {
$("#countDown").val("00:00:00");
}
}, 1000);
}
countdown();
});
I'm new in javascript.
My PHP script returns a value in this format
d:h:m:s
Now I would like to have a countdown which is able to countdown each second from this.
I modified a countdown. This works once a time, after the countdown "ticks" each second it returns NaN all the time. Any idea what I do wrong?
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
var days = Math.floor(timestamp / 86400);
console.log(time,timestamp);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - hours * 3600) / 60);
var seconds = timestamp - ((days * 86400) + (hours * 3600) + (minutes * 60))-1;
$(this).data("time",""+days+":"+hours+":"+minutes+":"+seconds);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
As far as I can see you have 2 problems here:
after the first execution you change the pattern of the text you display in the h1. First you have 02:03:05:59. Then you want to write 02 days 03:05:58 into the tag. Next time you parse it, you get the error because you split at : and that does not work anymore as you have days instead of : as the seperator for the first part.
When calculating the minutes, you should also substract the days and not just the hours.
When you wan to keep the dd:hh:mm:ss format, you could do it like this:
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).text().split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
timestamp -= timestamp > 0;
var days = Math.floor(timestamp / 86400);
console.log(days);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - days * 86400 - hours * 3600) / 60);
var seconds = timestamp - days * 86400 - hours * 3600 - minutes * 60;
if (days < 10) {
days = '0' + days;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
Your snippet goes from dd:hh:mm:ss to dd days, hh hours. So second time around, your tag contains non-parsable text.
I have changed it to something more precise. Something even MORE precise would be to give a timestamp in milliseconds in the future instead of something with seconds since it will take several seconds to render the page. If you round on minutes from the server, it would likely be better.
var aDay = 24*60*60*1000, anHour = 60*60*1000, aMin = 60*1000, aSec = 1000;
$(document).ready(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var date = new Date();
date.setDate(date.getDate()+parseInt(time[0],10))
date.setHours(date.getHours()+parseInt(time[1],10),date.getMinutes()+parseInt(time[2],10),date.getSeconds()+parseInt(time[3],10),0)
$(this).data("when",date.getTime());
});
setInterval(function() {
$('.countdown').each(function() {
var diff = new Date(+$(this).data("when"))-new Date().getTime();
var seconds, minutes, hours, days, x = diff / 1000;
seconds = Math.floor(x%60); x=(x/60|0); minutes = x % 60; x= (x/60|0); hours = x % 24; x=(x/24|0); days = x;
$(this).text(
days + ' day' +(days==1?", ":"s, ") +
hours + ' hour' +(hours==1?", ":"s, ") +
minutes + ' minute'+(minutes==1?", ":"s, ") +
seconds + ' second'+(seconds==1?".":"s.")
);
});
}, 500);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown" data-time="02:03:05:59"></h1>
I have the following code, which is supposed to do what I need:
function fromSeconds(seconds, showHours = false) {
if(showHours) {
var hours = Math.floor(seconds / 3600),
seconds = seconds - hours * 3600;
}
var minutes = (Math.floor(seconds/60) < 10) ?
"0" + Math.floor(seconds/60) : Math.floor(seconds/60);
var seconds = (seconds % 60 > 9) ? seconds % 60 : "0" + seconds % 60;
if(showHours) {
var timestring = hours + ":" + minutes + ":" + seconds;
} else {
var timestring = minutes + ":" + seconds;
}
return timestring;
}
The problems is that I also have this:
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function() {
$('#currentTime').html(video[0].currentTime.toFixed(2));
$('#remTime').html((video[0].duration - video[0].currentTime).toFixed(2));
$('#totalTime').html(video[0].duration.toFixed(2));
});
And I don't know how to apply the first code so that for example currentTime is displayed like this: minutes:seconds.
Any help please?
With a small fixation you can leave this as that:
Demo
function fromSeconds(seconds, showHours) {
if(showHours) {
var hours = Math.floor(seconds / 3600),
seconds = seconds - hours * 3600;
}
var minutes = ("0" + Math.floor(seconds/60)).slice(-2);
var seconds = ("0" + parseInt(seconds%60,10)).slice(-2);
if(showHours) {
var timestring = hours + ":" + minutes + ":" + seconds;
} else {
var timestring = minutes + ":" + seconds;
}
return timestring;
}
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
$('#currentTime').html(fromSeconds(video[0].currentTime));
$('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
$('#totalTime').html(fromSeconds(video[0].duration));
});
You can just pass the values like video[0].currentTime to the function fromSeconds which will return the formatted string
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
$('#currentTime').html(fromSeconds(video[0].currentTime));
$('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
$('#totalTime').html(fromSeconds(video[0].duration));
});
Assuming currentTime is the time in seconds, you need to pass the value into your function.
fromSeconds returns the text your require, so fromSeconds(mytimevalue) will return mm:ss as required:
video.bind("timeupdate", function() {
$('#currentTime').html( fromSeconds(video[0].currentTime) );
$('#remTime').html( fromSeconds(video[0].duration - video[0].currentTime) );
$('#totalTime').html( fromSeconds(video[0].duration) );
});
Another option would be to use JavaScript's Date() Object, which takes milliseconds as a value:
var currentTime = new Date(video[0].currentTime * 1000);
You can then use Date.getMinutes() and Date.getSeconds() to find your values.
More details here
$('#currentTime').html(function(){
var time=video[0].currentTime.toFixed(2);
//some conversion needed in-order to convert to required format
fromSeconds(time,false)//returns time
});
I don't know javascript. How to add minute to datadate in that html/javascript?
Example:
Datadate is 3,19--> Wednesday 7pm. I wanna make it 3,19,30--> Wednesday 7pm past half (7:30pm).
function getRemaining(EVENTDAY, EVENTHOUR, now) {
now = new Date();
var dow = now.getDay();
var hour = now.getHours() + now.getMinutes() / 60 + now.getSeconds() / 3600;
var offset = EVENTDAY - dow;
if (offset < 0 || (offset === 0 && EVENTHOUR < hour)) {
offset += 7;
}
var eventDate = now.getDate() + offset;
var eventTime = new Date(now.getFullYear(), now.getMonth(), eventDate,
EVENTHOUR, 0, 0);
var millis = eventTime.getTime() - now.getTime();
var seconds = Math.round(millis / 1000);
var minutes = Math.floor(seconds / 60);
seconds %= 60;
var hours = Math.floor(minutes / 60);
minutes %= 60;
var days = Math.floor(hours / 24);
hours %= 24;
if (seconds < 10) seconds = "0" + seconds;
if (minutes < 10) minutes = "0" + minutes;
if (hours < 10) hours = "0" + hours;
return days + "d " + hours + "h " + minutes + "m ";
}
function tick() {
$.each($('.countdown'), function (i, v) {
startdate = $(this).attr('datadate');
startdate = startdate.split(',');
$(this).html(getRemaining(startdate[0], startdate[1]));
});
}
setInterval(tick, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="countdown" datadate='6,19'></span>
<br>
<span class="countdown" datadate='2,19'></span>
<br>
<span class="countdown" datadate='3,19'></span>
<br>
<span class="countdown" datadate='3,20'></span>
<br>
Hope you can help me.
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
First of all, the last parameter from the function getRemaining(EVENTDAY, EVENTHOUR, now) is always null ( or undefined ). I removed the parameter and made a function-scoped variable.
I also made some visual changes to the code. Here You go, this should work:
function getRemaining(EVENTDAY, EVENTHOUR, EVENTMINUTE) {
var now = new Date();
var offset = EVENTDAY - now.getDay();
var hour = now.getHours() + now.getMinutes() / 60 + now.getSeconds() / 3600;
if (offset < 0 || (offset === 0 && EVENTHOUR < hour)) {
offset += 7;
}
var eventDate = now.getDate() + offset;
var eventTime = new Date(now.getFullYear(), now.getMonth(), eventDate, EVENTHOUR, EVENTMINUTE, 0);
var millis = eventTime.getTime() - now.getTime();
var seconds = Math.round(millis / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
seconds %= 60;
minutes %= 60;
hours %= 24;
if (seconds < 10) seconds = "0" + seconds;
if (minutes < 10) minutes = "0" + minutes;
if (hours < 10) hours = "0" + hours;
return days + "d " + hours + "h " + minutes + "m ";
}
function tick() {
$.each($('.countdown'), function (i, v) {
startdate = $(this).attr('datadate');
startdate = startdate.split(',');
$(this).html(getRemaining(startdate[0], startdate[1], startdate[2]));
});
}
setInterval(tick, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="countdown" datadate='6,5,8'></span>
<span class="countdown" datadate='3,10,30'></span>
You could use a library like moment.js
Then:
moment().format('MMMM Do YYYY, h:mm:ss a'); // February 12th 2015, 6:05:32 pm