I need for a clock to count from a specific time. e.g. Time is 20:08:00 and then to count from there. I have searched high and low for an answer and no one has specifically come up with an answer(that Ive seen). So my normal clock is like this.
<script type="text/javascript">
function clock()
{
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
if (minutes <= 9) minutes = "0" + minutes;
if (seconds <= 9) seconds = "0" + seconds;
dispTime = hours + ":" + minutes + ":" + seconds;
var basicclock = document.getElementById('basicclock');
basicclock.innerHTML = dispTime;
setTimeout("clock()", 1000);
}
clock();
</script>
So all I need is the time to start at say 20:08:00 (or a variable of time). I am wondering if it better to use a timer to achieve a set time and to count from that???
Any help would be appreciated.
First: Please try to extensively search SO for answers before asking questions, many helpful responses can be found if you look. ;)
If you are trying to countdown to a certain time/date I would recommend the answer found HERE
All code credit goes to author's answer above.
HTML - for display
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
Script (keep formatting and just modify the 4th line down for your target date)
setInterval(function(){
// set whatever future date / time you want here, together with
// your timezone setting...
var future = new Date("Sep 20 2014 21:15:00 GMT+0200");
var now = new Date();
var difference = Math.floor((future - now) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$("#seconds").text(seconds + "s");
$("#minutes").text(minutes + "m");
$("#hours").text(hours + "h");
$("#days").text(days + "d");
}, 1000);
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
DEMO OF THE ABOVE CODE
I would also look at these are other interesting solutions found on this post here HERE
Related
I'm getting my google api response for duration like 1 hour 13 minutes i need to covert this to 'hh:mm:ss' format.How to convert this in React js?
response:
distance: {text: "47.8 km", value: 47790}
duration:
text: "1 hour 13 mins"
value: 4378
__proto__: Object
status: "OK"
It seems the values that are provided: 44790 and 4378, are meters and seconds. Now that you have the seconds as a number you can do all sort of things to get them in the format you want. There are a lot of javascript snippets out there that can do this for you:
function convertHMS(value) {
const sec = parseInt(value, 10); // convert value to number if it's string
let hours = Math.floor(sec / 3600); // get hours
let minutes = Math.floor((sec - (hours * 3600)) / 60); // get minutes
let seconds = sec - (hours * 3600) - (minutes * 60); // get seconds
// add 0 if value < 10
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds; // Return is HH : MM : SS
}
const yourTime = convertHMS(4378); // 4378 seconds
// yourTime is 01:12:58
console.log(yourTime);
If you have a basic/beginning Javascript knowledge the only thing that might be funny business in this script are Math.floor() and parseInt().
credits to: https://www.4codev.com/javascript/convert-seconds-to-time-value-hours-minutes-seconds-idpx6943853585885165320.html in this case, you can find these ~10 lines anywhere though, I found them here after a few seconds of searching.
Always try to fix your problem in plain JS first before adding some sort of library that does the work for you, because you don't want to add a complete library for something that can be done in ~10 lines of plain JS. And ofcourse, plain JS works perfectly well in React =).
If you need to support IE6 - IE10 you might want to replace const and let with var (though I do not encourage supporting those browser if you don't have to from a business perspective).
edit: I'm fairly new to answering questions here so I converted the code to a code snippet.
Great solution, Sapulidi. I used your code with a slight modification. Posting for anyone interested.
In typescript
Hours only appear if there are >0 hours
const millisecondsToHHMMSS = (duration: number) => {
const sec = Math.round(duration / 1000);
const hours = Math.floor(sec / 3600); // get hours
const minutes = Math.floor((sec - hours * 3600) / 60); // get minutes
const seconds = sec - hours * 3600 - minutes * 60; // get seconds
// add 0 if value < 10
let sHours = hours > 0 ? `${hours}:` : '';
let sMinutes = `${minutes}`;
let sSeconds = `${seconds}`;
if (minutes < 10) {
sMinutes = '0' + sMinutes;
}
if (seconds < 10) {
sSeconds = '0' + sSeconds;
}
return sHours + sMinutes + ':' + sSeconds;
// Return is HH:MM:SS
};
let timeWithHours = 12345
let formattedWithHours = millisecondsToHHMMSS(timeWithHours)
let timeWithoutHours = 12345678
let formattedWithoutHours = millisecondsToHHMMSS(timeWithoutHours)
console.log(formattedWithHours)
console.log(formattedWithoutHours)
It is not related to React. You can simply use moment.js
moment(distance.value).format('hh:mm:ss');
You could either use one of the date formatting libraries (e.g. momentjs or date-fns) or just calculate it by yourself. You are getting the duration in seconds (it seems to be 4378 seconds), so calculating it by yourself won't be much of an effort.
Here is an example:
const values = getHoursMinutesAndSeconds(4378);
console.log(values);
console.log(`${zeroPadding(values.hours, 2)}:${zeroPadding(values.minutes, 2)}:${zeroPadding(values.seconds, 2)}`);
function getHoursMinutesAndSeconds (totalSeconds) {
// step 1: create seconds and hoursAndMinutes (minutes, but might be larger than 60)
const hoursAndMinutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
// step 2: create minutes and hours from hoursAndMinutes
const hours = Math.floor(hoursAndMinutes / 60);
const minutes = hoursAndMinutes % 60;
return { hours, minutes, seconds };
}
function zeroPadding (number, length) {
return String(number).padStart(length, '0');
}
I am trying to create countdown timer between 2 dates but the time is lagging behind after a while.
My PHP backend returns the difference between current time and X time in the future, for example current time and 2 hours in advance. This difference is passed to my HTML frontent in a .countdown class in the following format 03:20:15 which I use a javascript function to countdown the difference. Here is my function:
$(".countdown").each(function() {
var $e = $(this);
var interval = setInterval(function() {
var timer2 = $e.html();
var timer = timer2.split(':');
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if(hours < 0) {
clearInterval(interval);
window.location.reload();
} else {
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
$e.html(hours + ':' + minutes + ':' + seconds);
}
}, 1000);
});
The code works as expected but after a few minutes, lets say 2-3 minutes, if you refresh the page or open it in a new window you will see that the countdown timer was lagging behind by seconds/minutes. Does someone know what Im doing wrong?
You should compute the difference between (new Date()) and the target date. Use that difference and format new HTML string instead of parsing it to a hour, minutes, seconds value for decrementing.
details
The setInterval api specs suggest that delays due to CPU load, other tasks, etc, are to be expected.
https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
Your handler is called at approximately equal intervals while you consider them to be exact. At first iteration the actual time may differ from a planed time by some small amount (let say 4ms). Yet you are changing your counter by 1000 ms. As many more iterations passed this difference accumulates and become noticeable. A few minutes is enough to make this happens.
If you, on the other hand, pre-compute the target date-time value and will use the difference between current time and the target time your code will not be sensible to api inexactness.
$(".countdown").each(function () {
var $e = $(this);
const totalSeconds = (dt) => Math.floor(dt.valueOf() / 1000);
const f1 = (timer2) => {
var timer = timer2.split(':');
var tdt = new Date().setHours(
parseInt(timer[0]) + tdt.getHours(),
parseInt(timer[1]) + tdt.getMinutes(),
parseInt(timer[2]) + tdt.getSeconds());
return totalSeconds(tdt);
};
const targetTime = f1($e.html());
setInterval(function () {
var timeSpan = targetTime - totalSeconds(new Date());
if (timeSpan < 0) {
window.location.reload();
} else {
var seconds = timeSpan % 60;
var totalMinutes = Math.floor(timeSpan / 60);
var minutes = totalMinutes % 60;
var hours = Math.floor(totalMinutes / 60);
$e.html(hours + ':' + minutes + ':' + seconds);;
}
}, 1000);
});
see also:
https://jsfiddle.net/8dygbo9a/1/
I have found a code but i dont know to add timezone . i want to detect the timer from the timezone of the other country like denmark/copenhagen. thank you. this is my code.
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, hiden, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).val());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
$(hiden).val(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed","#stoppedid", 1);
timeLogger.start();
$("#confirm").click(function() { //Stop timer upon clicking the Confirm Button
timeLogger.stop();
});
});
</script>
thank you. i dont know javascript. i know php only. i tried to put
before the code is running. i already save a time from europe/copenhagen. but when the timer is running. it says 6:00:01 abd counting.. but i want to run like this 0:00:01 and counting. and my idea the time from europe and time in my country is 6 hours. i want to run the time from europe not my country. because i save the time from europe using php. see bellow the code for save the time.
date_default_timezone_set("Europe/Copenhagen");
but wont work. i didnt found the solution
Analyzing this code, I rewrote the needed HTML to see what the code do. It's simply creates a counter in format hh:mm:ss and shows on screen, this counter show the time passed since the date informed.
to add the user timezone to reflect in your timer, you just need to recalculate the seconds inside the prettyPrintTime(numSeconds) function before use it to get hours, minutes and seconds.
function prettyPrintTime(numSeconds) {
var tzOffset = new Date().getTimezoneOffset(); // get the timezone in minutes
tzOffset = tzOffset * 60; // convert minutes to seconds
numSeconds -= tzOffset; // recalculate the time using timezone
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
Take a look at the working code:
https://jsfiddle.net/4c6xdcpr/
function getClientTimeZone() {
var offset = new Date().getTimezoneOffset(),
o = Math.abs(offset);
return (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);
}
// Display Output
alert(getClientTimeZone());
I have an HTML Table used to generate a Calendar which shows TimeClock entries for each day a user has worked and clocked in and out of the system. Each day also shows the total time duration for each clock in/out entry. (multiple "timecard punches" can be within the same day)
Simply put I have DateTime style strings which hold a Duration value and I need to add them all together to get a combined duration value.
In a loop this JavaScript variable totalTimeValue will be assigned a duration value as a text string like this 03:31:23
Add these duration strings together using JavaScript...
03:31:23
04:21:56
04:08:42
03:31:17
04:10:59
02:48:21
04:26:11
00:00:39
03:41:37
Using JavaScript and jQuery I have this code below which gets the DateTime Duration value as a string in the format 04:21:19 for each timeclock entry.
My JavaScript/jQuery so far...
Demo of it working here: http://codepen.io/jasondavis/pen/GpPPPR?editors=101
var totalTimeValue = 0;
var totalWeekTimeValue = 0;
// itterate each week which is table row <tr>
$('#timeclock-cal > tbody > tr').each(function() {
console.log('=== New Week ===');
totalWeekTimeValue = 0;
// get each day which is a table cell <td>
$(this).find('td').each(function() {
console.log('== New Day ==');
// get total time val for each clock in/out on each day which is inside
// button with CSS class .cal-punch-total-time
$(this).find('.cal-punch-total-time').each(function() {
totalTimeValue = $(this).text();
console.log(totalTimeValue);
// THIS PART NEEDS YOUR HELP!
// NEED TO ADD EACH DATETIME STRING TOGETHER FOR TOTAL DURATION VALUES
totalWeekTimeValue = totalTimeValue+totalWeekTimeValue;
});
});
console.log('= total week time === '+totalWeekTimeValue);
});
full size image
I have no objection to using the MomentJS library http://momentjs.com/ if it can help in this situation however my research so far did not really show any examples doing what I need to do in this question.
In fact all my StackOverflow and Google searches resulted in no examples of adding durations like this in JavaScript!
I did find this MomentJS plugin MomentJS Durations - https://github.com/jsmreese/moment-duration-format
With JQuery and Javascript its easily possible. Please have a look at below code.
$(document).ready(function(){
var pad = function(num) { return ("0"+num).slice(-2); }
var totalSeconds = 0;
$("li").each(function(){
var currentDuration = $(this).text();
currentDuration = currentDuration.split(":");
var hrs = parseInt(currentDuration[0],10);
var min = parseInt(currentDuration[1],10);
var sec = parseInt(currentDuration[2],10);
var currDurationSec = sec + (60*min) + (60*60*hrs);
totalSeconds +=currDurationSec;
});
var hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
var minutes = Math.floor(totalSeconds / 60);
var seconds = totalSeconds % 60;
$(".totalVal").text(pad(hours)+":"+pad(minutes)+":"+pad(seconds));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
<li>03:31:23</li>
<li>04:21:56</li>
<li>04:08:42</li>
<li>03:31:17</li>
<li>04:10:59</li>
<li>02:48:21</li>
<li>04:26:11</li>
<li>00:00:39</li>
<li>03:41:37</li>
</ul>
<div id="totalTime">Total Time:<span class="totalVal"></span></div>
This is a little overkill, but shows how to use map and reduce.
/** Calculate the number of seconds from HH:MM:SS **/
function getSeconds(time) {
var parts = time.split(":");
return parseInt(parts[0], 10) * 3600 + parseInt(parts[1], 10) * 60 + parseInt(parts[2], 10);
}
//select all the elements
var totalSeconds = $("a.cal-punch-total-time")
.map( function(ind, elem) { //convert the jQuery object into the array
var text = $(elem).text(); //get the text from the anchor
return getSeconds(text); //set the index to the total seconds
})
.get() //gets the array out of the jQuery object
.reduce( function(runningTotal, currentValue){ //Now to combine all the values into one
return runningTotal + currentValue; //sum up the values
},0); //The initial starting vaule
//Now get the hour, minutes, and seconds from the total seconds
var hours = parseInt( totalSeconds / 3600 );
var minutes = parseInt( totalSeconds / 60 ) % 60;
var seconds = totalSeconds % 60;
//left pad numbers less than ten
if(hours<10) hours = "0" + hours;
if(minutes<10) minutes = "0" + minutes;
if(seconds<10) seconds = "0" + seconds;
$("#out").html("Total Time: " + (hours + ":" + minutes + ":" + seconds));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cal-punch-total-time">03:31:23</a>
<a class="cal-punch-total-time">04:21:56</a>
<a class="cal-punch-total-time">04:08:42</a>
<a class="cal-punch-total-time">03:31:17</a>
<a class="cal-punch-total-time">04:10:59</a>
<a class="cal-punch-total-time">02:48:21</a>
<a class="cal-punch-total-time">04:26:11</a>
<a class="cal-punch-total-time">00:00:39</a>
<a class="cal-punch-total-time">03:41:37</a>
<div id="out"></div>
Try this:
function hhmmssToSeconds(str) {
var arr = str.split(':').map(Number);
return (arr[0] * 3600) + (arr[1] * 60) + arr[2];
};
function secondsToHHMMSS(seconds) {
var hours = parseInt(seconds / 3600, 10),
minutes = parseInt((seconds / 60) % 60, 10),
seconds = parseInt(seconds % 3600 % 60, 10);
return [hours, minutes, seconds].map(function (i) { return i.toString().length === 2 ? i : '0' + i; }).join(':');
}
Then:
var t1 = hhmmssToSeconds('40:50:40'),
t2 = hhmmssToSeconds('04:12:30');
var result = secondsToHHMMSS(t1 + t2); // '45:03:10'
You can split your DateTime strings into arrays.
totalTimeValue = $(this).text().split(':'); //from '03:10:30' to ['03','10','30']
Then loop through your array and coerce each string to a number.
totalTimeValue.forEach(function(val,idx){
totalWeekTimeValue[idx] += Number(val);
});
This will leave you with an array of values for totalWeekTime that you can format/recalculate and rejoin if needed.
totalWeekTimeValue.join(':'); //[3:10:30]
http://codepen.io/hirechrismeyers/pen/ZbVVgr
In JavaScript I have a variable Time in milliseconds.
I would like to know if there is any build-in function to convert efficiently this value to Minutes:Seconds format.
If not could you please point me out a utility function.
Example:
FROM
462000 milliseconds
TO
7:42
Just create a Date object and pass the milliseconds as a parameter.
var date = new Date(milliseconds);
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
alert(((h * 60) + m) + ":" + s);
Thanks guys for your support, at th end I came up with this solution. I hope it can helps others.
Use:
var videoDuration = convertMillisecondsToDigitalClock(18050200).clock; // CONVERT DATE TO DIGITAL FORMAT
// CONVERT MILLISECONDS TO DIGITAL CLOCK FORMAT
function convertMillisecondsToDigitalClock(ms) {
hours = Math.floor(ms / 3600000), // 1 Hour = 36000 Milliseconds
minutes = Math.floor((ms % 3600000) / 60000), // 1 Minutes = 60000 Milliseconds
seconds = Math.floor(((ms % 360000) % 60000) / 1000) // 1 Second = 1000 Milliseconds
return {
hours : hours,
minutes : minutes,
seconds : seconds,
clock : hours + ":" + minutes + ":" + seconds
};
}
In case you already using Moment.js in your project, you can use the moment.duration function
You can use it like this
var mm = moment.duration(37250000);
console.log(mm.hours() + ':' + mm.minutes() + ':' + mm.seconds());
output: 10:20:50
See jsbin sample
It's easy to make the conversion oneself:
var t = 462000
parseInt(t / 1000 / 60) + ":" + (t / 1000 % 60)
You may like pretty-ms npm package: https://www.npmjs.com/package/pretty-ms
If that what you are searching. Headless nice formatting (time in the units that are needed as ms grow), personalisable, and cover different situations. Small and efficient for what it cover.
function msToMS(ms) {
var M = Math.floor(ms / 60000);
ms -= M * 60000;
var S = ms / 1000;
return M + ":" + S;
}