Lost trying to create a stopwatch - javascript

I'm trying to self-taugh JavaScript and while doing some texts with a stopwatch I got lost into this problem. It's working but it's always starting on 95:34:47 instead of 00:00:00
This is what i tried so far.
<script>
/*Timer Stuff*/
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
I understand that I need to subtract an specific amount of time to match the timer accurately, however I can't figure out how to do it.

You need to store a variable with the start time, and subtract from that. The 95 you're getting for the hours is actually much higher, just being cropped, being that you're calculating from the Unix epoch.
I would just do it something like this:
function update() {
var d = new Date();
var n = d - startTime;
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
startTime = new Date();
MyVar = setInterval(update, 1);
}
Note that you don't even need to use d.getTime() when subtracting -- you can just subtract Date objects themselves.

You have to introduce a start-time variable.
In every update-step you have to get the difference from start to now.
For your code:
<script>
/*Timer Stuff*/
timestart = new Date();
timestart_time = timestart.getTime();
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
time = time -timestart_time;
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
That works for me :)

Related

Can't I run multiple javascript functions with setInterval on a page?

Update
Turns out, coding while tired is not optimal. As pointed out in the comments, I was missing the definition of oneHour in countdownAutoLogout()... It must have been accidentally deleted in the copy & paste-process... Sorry for the inconvenience! I'll show myself out.
I have two almost identical countdown functions located in site.js. One is working, the other not so much.
I used to have only countdownAutoLogout(), and it was working as expected. Upon adding countdownMeeting(durationSeconds), countdownAutoLogout() is only initiated, but doesn't count down, as I have illustrated with the alert()s in the code.
countdownAutoLogout() is called in the <body>-tag in _Layout.cshtml:
<body onload="javascript: countdownAutoLogout();">
countdownMeeting(durationSeconds) is called in the scripts section in the view:
#section scripts{
<script>
$(document).ready(function() {
// Model.RemainingSeconds is a model property of type double.
countdownMeeting(#Model.RemainingSeconds);
})
</script>
}
The functions:
// Padding with leading zero:
function pad(str, max, padder) {
padder = typeof padder === "undefined"
? "0"
: padder;
return str.toString().length < max
? pad(padder.toString() + str, max, padder)
: str;
}
function countdownAutoLogout() {
alert("This alert pops up.");
var oneMinute = 60000;
var twoHours = oneMinute * 121;
var countDownDate = Date.now() + twoHours;
var x = setInterval(function () {
var now = Date.now();
var distance = countDownDate - now;
var hours = Math.floor((distance % (oneHour * 24)) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
alert("This alert doesn't pop up.");
document.getElementById("SessionCookieExpirationCountdown").innerHTML =
pad(hours, 2) + ":" + pad(minutes, 2);
if (distance < 0) {
clearInterval(x);
location.href = "/Home/Timeout";
}
}, 5000);
}
// This function is working smoothly:
function countdownMeeting(durationSeconds) {
var oneMinute = 60000;
var oneHour = oneMinute * 60;
var duration = oneMinute * durationSeconds / 60;
var countDownDate = Date.now() + duration;
var x = setInterval(function () {
var now = Date.now();
var distance = countDownDate - now;
var hours = Math.floor((distance % (oneHour * 24)) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / 1000);
document.getElementById("MeetingDurationCountdown").innerHTML =
pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2);
if (distance < 0) {
clearInterval(x);
document.getElementById("MeetingDurationCountdown").innerHTML = "Overtime!";
}
}, 1000);
}

How to get UTC timezone in javascript and adjust to PDT/PT

I have a countdown timer timer constructed but it's just using getTime(), i'm unsure how to adjust this so it is the correct timezone i want (PDT/PT)
var countdownTimer = setInterval(countdownTick, 1000);
function countdownTick() {
jQuery('ul.countdown').each(function() {
var date = jQuery(this).attr('data-date').split('-'); // Create date array from attribute
var time = jQuery(this).attr('data-time').split('-'); // Create time array from attribute
for (var i = 0; i < date.length; i++) {
date[i] = parseInt(date[i]);
}
for (var i = 0; i < time.length; i++) {
time[i] = parseInt(time[i]);
}
var today = new Date();
var theDate = new Date(date[0], (date[1] - 1), date[2], time[0], time[1]);
if (theDate.getTime() > today.getTime()) { // If the target date is in the future
countdownCalc(this, theDate, today); // Calculate how much time there is until the target date
}
});
}
function countdownCalc(obj, targetDate, currentDate) {
var oneDay = 1000 * 60 * 60 * 24;
var oneSecond = 1000;
var output = (targetDate.getTime() - currentDate.getTime());
var day = Math.floor(output / oneDay);
var hour = Math.floor((output - (day * oneDay)) / (1000 * 60 * 60));
var minute = Math.floor((output - (hour * (1000 * 60 * 60) + (day * oneDay))) / (1000 * 60));
var second = Math.floor((output - ((minute * 60000) + (hour * 1000 * 60 * 60) + (day * oneDay))) / 1000);
jQuery(obj).html('<li><span class="countdown-label">DAYS</span><span class="countdown-number">' + day + '</span></li><li><span class="countdown-label">HOURS</span><span class="countdown-number">' + hour + '</span></li><li><span class="countdown-label">MINUTES</span><span class="countdown-number">' + minute + '</span></li><li><span class="countdown-label">SECONDS</span><span class="countdown-number">' + second + '</span></li>');
}
https://jsfiddle.net/4nag4h5v/
Here is where plugins become useful, using moment-timezone.js
We are able to do something is simple as:
let time = Date.now();
moment(time).tz("YOURTIMEZONE").format('x') // get timestamp (in milliseconds
Without using an external library, the simplest way to do it is by using an offset between your local and target timezones:
let today = new Date(),
localOffset = -(today.getTimezoneOffset()/60),
targetOffset = -8,
netOffset = targetOffset - targetOffset;
const d = new Date(new Date().getTime() + netOffset * 3600 * 1000);

calculate time difference between two date in HH:MM:SS javascript

I have created one timer application in javascript.
Firstly it takes the current UTC date to init timer with some reference. here's the code
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
var current_date = this.get_current_UTCDate();
this.project_timesheet_db.set_current_timer_activity({date: current_date});
this.start_interval();
this.initialize_timer();
this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");
Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.
This function is
start_interval: function() {
var timer_activity = this.project_timesheet_db.get_current_timer_activity();
var self = this;
this.intervalTimer = setInterval(function(){
self.$el.find(".pt_duration").each(function() {
var el_hour = $(this).find("span.hours");
var el_minute = $(this).find("span.minutes");
var minute = parseInt(el_minute.text());
if(minute >= 60) {
el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
minute = 0;
}
el_minute.text(_.str.sprintf("%02d", minute));
var el_second = $(this).find("span.seconds");
var seconds = parseInt(el_second.text()) + 1;
if(seconds > 60) {
el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
seconds = 0;
}
el_second.text(_.str.sprintf("%02d", seconds));
});
}, 1000);
},
Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.
thanks in advance for help
To convert H:M:S to seconds, you can use a simple function like:
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
Then to convert seconds back to HMS:
// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
var a = '01:43:28';
var b = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18
You may want to abbreviate the function names to say:
toHMS(toSec(a) - toSec(b)); // -10:39:18
Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.
Edit
The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.
If you have Date objects, you can get the difference between them in milliseconds using:
var diffMilliseconds = date0 - date1;
and convert to seconds:
var diffSeconds = diffMilliseconds / 1000;
and present as HH:MM:SS using the secondsToHMS function above:
secondsToHMS((date0 - date1) / 1000);
e.g.
var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);
console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18
I think there is a simpler solution.
function dateDiffToString(a, b){
// make checks to make sure a and b are not null
// and that they are date | integers types
diff = Math.abs(a - b);
ms = diff % 1000;
diff = (diff - ms) / 1000
ss = diff % 60;
diff = (diff - ss) / 60
mm = diff % 60;
diff = (diff - mm) / 60
hh = diff % 24;
days = (diff - hh) / 24
return days + ":" + hh+":"+mm+":"+ss+"."+ms;
}
var today = new Date()
var yest = new Date()
yest = yest.setDate(today.getDate()-1)
console.log(dateDiffToString(yest, today))
const dateDiffToString = (a, b) => {
let diff = Math.abs(a - b);
let ms = diff % 1000;
diff = (diff - ms) / 1000;
let s = diff % 60;
diff = (diff - s) / 60;
let m = diff % 60;
diff = (diff - m) / 60;
let h = diff;
let ss = s <= 9 && s >= 0 ? `0${s}` : s;
let mm = m <= 9 && m >= 0 ? `0${m}` : m;
let hh = h <= 9 && h >= 0 ? `0${h}` : h;
return hh + ':' + mm + ':' + ss;
};
This may be the simple answer
var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
More intuitive and easier to read.
function hmsToSeconds(t) {
const [hours, minutes, seconds] = t.split(':')
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
}
function secondsToHMS(secs) {
return new Date(secs * 1000).toISOString().substr(11, 8)
}
var startTime = '01:43:28';
var endTime = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18

Convert "stopwatch" time to hourly

I have a stopwatch timer built in JS that counts up from 0 using hours, minutes, seconds and milliseconds. Currently when the user hits the stop button the value from the timer is appended to a hidden input element for form submission. I need to convert whatever the time is to just hourly to where it is appended to that hidden input. So right now if my clock is stopped at 25 minutes and 00 seconds, the value in the input is 00:25:00, I would like it to convert the time to something like .25 (for hours)
For example, for 30 minutes the value appended to my hidden input would be .5, for 45 minutes it would be .75, so on and so fourth.
Here is the stopwatch script, the Stop function is where the value is appended to our hidden input, just need to make sure it is converted to hourly
<script type="text/javascript">
var clsStopwatch = function () {
var startAt = 0;
var lapTime = 0;
var now = function () {
return (new Date()).getTime();
};
this.start = function () {
startAt = startAt ? startAt : now();
};
this.stop = function () {
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0;
};
this.time = function () {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor(time / (3600 * 1000));
time = time % (3600 * 1000);
m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2);
//newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
return newTime;
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}
</script>
If I correctly understand what you need, this is your solution:
function millisecondsToHours(amountMS) {
return amountMS / 3600000;
}

subtract minutes from calculated time javascript

I need to subtract minutes from the calculated time
var calculatedTime=11.30;// hours
var subtractTime=40;//minutes
var diff=calculatedTime - subtractTime;// How to do this ??
How to do this in javascript
Thanks
Try this:
function converToMinutes(s) {
var c = s.split('.');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
function parseTime(s) {
return Math.floor(parseInt(s) / 60) + "." + parseInt(s) % 60
}
//var minutes = parseTime(EndTIme) - parseTime(StartTime);
var timeToSubtract = 40;
var startTime = converToMinutes('11.30');
var converted = parseTime(startTime - timeToSubtract);
alert(converted);
Demo here

Categories