.getTime when $(document).ready for countdown - javascript

I want to make a countdown. Here's the algorithm :
var timeFinish, timeStart, timeNow, duration
timeStart <- the time when the document has ready
timeFinish <- timeStart + 1hour
timeNow <- get the time everytime (every second)
duration <- timeFinish - timeNow
output (duration)
I deliberately didn't write the algorithm for converting it into second etc (for shortening purpose, and I hope you get what I mean). Here's my code
$(document).ready(function() {
setInterval(countdown(), 1000);
function countdown() {
var hStart = new Date($(document).ready).getHours;
var mStart = new Date($(document).ready).getMinutes;
var sStart = new Date($(document).ready).getSeconds;
var secondTotalStart = (hStart * 3600) + (mStart * 60) + sStart;
var secondTotalFinish = secondTotalStart + 3600;
var hRunning = new Date().getHours;
var mRunning = new Date().getMinutes;
var sRunning = new Date().getSeconds;
var secondTotalRunning = (hRunning * 3600) + (mRunning * 60) + sRunning;
var duration = secondTotalFinish - secondTotalRunning;
var h = Math.floor(duration / 3600);
var m = Math.floor(duration % 3600) / 60;
var s = Math.floor(duration % 3600) % 60;
$("#countdown").html(h + " h : " + m + " m : " + s + " s");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
And my question is, how to get the timeStart? And is my code wrong?

I've corrected your code so you can look at mistakes:
$(document).ready(function() {
//below line: you must pass countdown as a function
setInterval(countdown, 1000);
var dt = new Date(); //get this out of countdown function
var hStart = dt.getHours();
var mStart = dt.getMinutes();
var sStart = dt.getSeconds();
var secondTotalStart = (hStart * 3600) + (mStart * 60) + sStart;
var secondTotalFinish = secondTotalStart + 3600;
function countdown() {
var cdt = new Date();
var hRunning = cdt.getHours();
var mRunning = cdt.getMinutes();
var sRunning = cdt.getSeconds();
var secondTotalRunning = (hRunning * 3600) + (mRunning * 60) + sRunning;
var duration = secondTotalFinish - secondTotalRunning;
var h = Math.floor(duration / 3600);
var m = Math.floor(duration % 3600 / 60);
var s = Math.floor(duration % 3600) % 60;
$("#countdown").html(h + " h : " + m + " m : " + s + " s");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>

$(document).ready(function() {
var dTime = new Date(); //need to store the on-load time before set interval as a reference
setInterval(countdown, 1000);
function countdown() {
var hStart = dTime.getHours();//need to get the on-load hr, min and sec from the previously stored time.
var mStart = dTime.getMinutes();
var sStart = dTime.getSeconds();
var secondTotalStart = (hStart * 3600) + (mStart * 60) + sStart;
var secondTotalFinish = secondTotalStart + 3600;
var running = new Date()// store the current time into a variable
var hRunning = running.getHours();
var mRunning = running.getMinutes();
var sRunning = running.getSeconds();
var secondTotalRunning = (hRunning * 3600) + (mRunning * 60) + sRunning;
var duration = secondTotalFinish - secondTotalRunning;
var h = Math.floor(duration / 3600);
var m = Math.floor(duration % 3600) / 60;
var s = Math.floor(duration % 3600) % 60;
$("#countdown").html(h + " h : " + m + " m : " + s + " s");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
Did minor corrections. hope this helps
edit:
added some useful comments.

Related

Get difference between two times with ss.[milisecond] format [duplicate]

I have this function which formats seconds to time
function secondsToTime(secs){
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return minutes + ":" + seconds;
}
it works great but i need a function to turn milliseconds to time and I cant seem to understand what i need to do to this function to return time in this format
mm:ss.mill
01:28.5568
Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
If you want it formatted as hh:mm:ss.sss then use:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
function pad(n, z) {
z = z || 2;
return ('00' + n).slice(-z);
}
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);
}
console.log(msToTime(55018))
Using some recently added language features, the pad function can be more concise:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
var pad = (n, z = 2) => ('00' + n).slice(-z);
return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);
}
// Current hh:mm:ss.sss UTC
console.log(msToTime(new Date() % 8.64e7))
Here is my favourite one-liner solution:
new Date(12345 * 1000).toISOString().slice(11, -1); // "03:25:45.000"
Method Date.prototype.toISOString() returns a string in the simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. This method is supported in all modern browsers (IE9+) and Node.
This one-liner is limited to a range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). The following code is able to format correctly any number of milliseconds (shaped in a handy prototype method):
/**
* Convert (milli)seconds to time string (hh:mm:ss[:mss]).
*
* #param Boolean seconds
*
* #return String
*/
Number.prototype.toTimeString = function(seconds) {
var _24HOURS = 8.64e7; // 24*60*60*1000
var ms = seconds ? this * 1000 : this,
endPos = ~(4 * !!seconds), // to trim "Z" or ".sssZ"
timeString = new Date(ms).toISOString().slice(11, endPos);
if (ms >= _24HOURS) { // to extract ["hh", "mm:ss[.mss]"]
var parts = timeString.split(/:(?=\d{2}:)/);
parts[0] -= -24 * Math.floor(ms / _24HOURS);
timeString = parts.join(":");
}
return timeString;
};
console.log( (12345 * 1000).toTimeString() ); // "03:25:45.000"
console.log( (123456 * 789).toTimeString() ); // "27:03:26.784"
console.log( 12345. .toTimeString(true) ); // "03:25:45"
console.log( 123456789. .toTimeString(true) ); // "34293:33:09"
function millisecondsToTime(milli)
{
var milliseconds = milli % 1000;
var seconds = Math.floor((milli / 1000) % 60);
var minutes = Math.floor((milli / (60 * 1000)) % 60);
return minutes + ":" + seconds + "." + milliseconds;
}
Why not use the Date object like this?
let getTime = (milli) => {
let time = new Date(milli);
let hours = time.getUTCHours();
let minutes = time.getUTCMinutes();
let seconds = time.getUTCSeconds();
let milliseconds = time.getUTCMilliseconds();
return hours + ":" + minutes + ":" + seconds + ":" + milliseconds;
}
https://jsfiddle.net/4sdkpso7/6/
function millisecondsToTime(millisecs){
var ms = Math.abs(millisecs) % 1000;
var secs = (millisecs < 0 ? -1 : 1) * ((Math.abs(millisecs) - ms) / 1000);
ms = '' + ms;
ms = '000'.substring(ms.length) + ms;
return secsToTime(secs) + '.' + ms;
}
Here is a filter that use:
app.filter('milliSecondsToTimeCode', function () {
return function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100)
, seconds = parseInt((duration / 1000) % 60)
, minutes = parseInt((duration / (1000 * 60)) % 60)
, hours = parseInt((duration / (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;
};
});
Just add it to your expression as such
{{milliseconds | milliSecondsToTimeCode}}
Editing RobG's solution and using JavaScript's Date().
function msToTime(ms) {
function addZ(n) {
return (n<10? '0':'') + n;
}
var dt = new Date(ms);
var hrs = dt.getHours();
var mins = dt.getMinutes();
var secs = dt.getSeconds();
var millis = dt.getMilliseconds();
var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
return tm;
}
Prons:
simple and clean code; easy to modify for your needs
support any amount of hours (>24 hrs is ok)
format time as 00:00:00.0
You can put it into a helper file
export const msecToTime = ms => {
const milliseconds = ms % 1000
const seconds = Math.floor((ms / 1000) % 60)
const minutes = Math.floor((ms / (60 * 1000)) % 60)
const hours = Math.floor((ms / (3600 * 1000)) % 3600)
return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
seconds < 10 ? '0' + seconds : seconds
}.${milliseconds}`
}
This worked for me:
var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
JSFiddle
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
export function getFormattedDateAndTime(startDate) {
if (startDate != null) {
var launchDate = new Date(startDate);
var day = launchDate.getUTCDate();
var month = monthNames[launchDate.getMonth()];
var year = launchDate.getFullYear();
var min = launchDate.getMinutes();
var hour = launchDate.getHours();
var time = launchDate.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
return day + " " + month + " " + year + " - " + time + "" ;
}
return "";
}
function msToTime(s) {
var d = new Date(s);
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
d.getFullYear() + " "
+ ("0" + d.getHours()).slice(-2)
+ ":" + ("0" + d.getMinutes()).slice(-2)
+ ":" + ("0" + d.getSeconds()).slice(-2)
+"."+d.getMilliseconds();
return datestring;
}
output
16-10-2019 18:55:32.605
var
/**
* Parses time in milliseconds to time structure
* #param {Number} ms
* #returns {Object} timeStruct
* #return {Integer} timeStruct.d days
* #return {Integer} timeStruct.h hours
* #return {Integer} timeStruct.m minutes
* #return {Integer} timeStruct.s seconds
*/
millisecToTimeStruct = function (ms) {
var d, h, m, s;
if (isNaN(ms)) {
return {};
}
d = ms / (1000 * 60 * 60 * 24);
h = (d - ~~d) * 24;
m = (h - ~~h) * 60;
s = (m - ~~m) * 60;
return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
},
toFormattedStr = function(tStruct){
var res = '';
if (typeof tStruct === 'object'){
res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
}
return res;
};
// client code:
var
ms = new Date().getTime(),
timeStruct = millisecToTimeStruct(ms),
formattedString = toFormattedStr(timeStruct);
alert(formattedString);
var secondsToTime = function(duration) {
var date = new Date(duration);
return "%hours:%minutes:%seconds:%milliseconds"
.replace('%hours', date.getHours())
.replace('%minutes', date.getMinutes())
.replace('%seconds', date.getSeconds())
.replace('%milliseconds', date.getMilliseconds());
}
try this function :-
function msToTime(ms) {
var d = new Date(null)
d.setMilliseconds(ms)
return d.toLocaleTimeString("en-US")
}
var ms = 4000000
alert(msToTime(ms))
A possible solution that worked for my case. It turns milliseconds into hh:ss time:
function millisecondstotime(ms) {
var x = new Date(ms);
var y = x.getHours();
if (y < 10) {
y = '0' + y;
}
var z = x.getMinutes();
if (z < 10) {
z = '0' + z;
}
return y + ':' + z;
}
This is the solution I got and working so good!
function msToHuman(duration) {
var milliseconds = parseInt((duration%1000)/100)
seconds = parseInt((duration/1000)%60)
minutes = parseInt((duration/(1000*60))%60)
hours = parseInt((duration/(1000*60*60))%24);
return hours + "hrs " minutes + "min " + seconds + "sec " + milliseconds + 'ms';
}
Most of the answers don't cover cases where there is more than 24h. This one does.
I suggest extending Date object:
class SuperDate extends Date {
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
console.log('marathon', new SuperDate(11235200).raceTime)
console.log('ironman', new SuperDate(40521100).raceTime)
console.log('spartathlon', new SuperDate(116239000).raceTime)
console.log('epoch', new SuperDate(new Date()).raceTime)
This approach works great with Firestore Timestamp objects which are similar to what you need:
class SuperDate extends Date {
fromFirestore (timestamp) {
return new SuperDate(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000)
}
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
const timestamp = {seconds: 11235, nanoseconds: 200000000}
console.log('timestamp', new SuperDate().fromFirestore(timestamp))
console.log('marathon', new SuperDate().fromFirestore(timestamp).raceTime)
Simplest Way
let getTime = (Time)=>{
let Hours = Time.getHours();
let Min = Time.getMinutes();
let Sec = Time.getSeconds();
return `Current time ${Hours} : ${Min} : ${Sec}`;
}
console.log(getTime(new Date()));
An Easier solution would be the following:
var d = new Date();
var n = d.getMilliseconds();

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);
}

$this isn't working inside a function which is inside an .each() function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I have the below code, I believe the $this is not firing in the if statements as it is not adding either class. However, if I change it to look just for the class without the $this it adds both classes (because I have 2 coupons on the page, 1 which triggers the if and 1 that triggers the elseif). I am unsure on how to make the $this.find() trigger inside the if statement.
jQuery(document).ready(function($) {
if ($('.clockdiv')[0]) {
$('.couponWrap .coupons li').each(function() {
// Set the date we're counting down to
var deadlineYear = $(this).find("div .clockdiv .year").attr("rel");
var deadlineMonth = $(this).find("div .clockdiv .month").attr("rel");
var deadlineDay = $(this).find("div .clockdiv .days").attr("rel");
var deadlineHour = $(this).find("div .clockdiv .hours").attr("rel");
var deadlineMinute = $(this).find("div .clockdiv .minutes").attr("rel");
var deadlineSecond = $(this).find("div .clockdiv .seconds").attr("rel");
var couponExpired = $(this).find("div .clockdiv").attr("rel");
var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
var startDate = new Date($(this).find("div .clockdiv .start").attr("rel"));
// 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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}
//Works but only for 1st start date
//var testDate = $("div .clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var startDateNewer = new Date(startDate);
var newOldDate = new Date(startDateNewer.setDate(startDateNew.getDate() + 7));
//alert(startDate + ", " + startDateNew + ", " + startDateNewer + ", " + newOldDate);
//This works fine
var nowDateNew = new Date().getTime();
//alert(nowDateNew - newOldDate.getTime());
if (days <= 7) {
$(this).find('div.couponDiv').addClass("old-coupon");
} else if ((nowDateNew - newOldDate.getTime()) < 0) {
$(this).find('div.couponDiv').addClass("new-coupon");
}
}, 1000);
});
}
});
The specific code snippet in question is:
if (days <= 7) {
$(this).find('div.couponDiv').addClass("old-coupon");
} else if ((nowDateNew - newOldDate.getTime()) < 0) {
$(this).find('div.couponDiv').addClass("new-coupon");
}
just set var outside the function for example:
jQuery(document).ready(function($) {
if ($('.clockdiv')[0]) {
$('.couponWrap .coupons li').each(function() {
// Set the date we're counting down to
var deadlineYear = $(this).find("div .clockdiv .year").attr("rel");
var deadlineMonth = $(this).find("div .clockdiv .month").attr("rel");
var deadlineDay = $(this).find("div .clockdiv .days").attr("rel");
var deadlineHour = $(this).find("div .clockdiv .hours").attr("rel");
var deadlineMinute = $(this).find("div .clockdiv .minutes").attr("rel");
var deadlineSecond = $(this).find("div .clockdiv .seconds").attr("rel");
var couponExpired = $(this).find("div .clockdiv").attr("rel");
var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
var startDate = new Date($(this).find("div .clockdiv .start").attr("rel"));
// Update the count down every 1 second
var that = $(this);// out side the interval
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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}
//Works but only for 1st start date
//var testDate = $("div .clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var startDateNewer = new Date(startDate);
var newOldDate = new Date(startDateNewer.setDate(startDateNew.getDate() + 7));
//alert(startDate + ", " + startDateNew + ", " + startDateNewer + ", " + newOldDate);
//This works fine
var nowDateNew = new Date().getTime();
//alert(nowDateNew - newOldDate.getTime());
if (days <= 7) {
that.find('div.couponDiv').addClass("old-coupon");
} else if ((nowDateNew - newOldDate.getTime()) < 0) {
that.find('div.couponDiv').addClass("new-coupon");
}
}, 1000);
});
}
});

Dateformat in javascript

I would like to get the date difference:
var dateString='2015-04-07T10:46:25Z';
var dt = new Date(value);
var now = new Date();
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
var utc1 = Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate());
var utc2 = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
var days=Math.floor((utc2 - utc1) / _MS_PER_DAY);//this is 415
The result must be in this format: 415d, 03:06:33
What would be the best way to do that? I get date, but time is missing.
Try this
var datetime = new Date("2015-04-07T10:46:25Z");
var now = new Date();
if (datetime < now) {
var diffTime = now - datetime;
}else{
var diffTime = datetime - now;
}
var days = Math.floor(diffTime / 1000 / 60 / (60 * 24));
var dateDiff = new Date( diffTime );
var hour = dateDiff .getHours().toString().length == 1 ? '0' + dateDiff .getHours() : dateDiff .getHours();
var minute = dateDiff.getMinutes().toString().length == 1 ? '0' + dateDiff.getMinutes() : dateDiff.getMinutes();
var seconds = dateDiff.getSeconds().toString().length == 1 ? '0' + dateDiff.getSeconds() : dateDiff.getSeconds();
console.log(days + "d "+ hour + ":" + minute + ":" + seconds);
you need to use Modulus
var dt = new Date('2015-04-07T10:46:25Z');
var now = new Date();
var milSecondMil = 1000;
var secondMil = milSecondMil * 60;
var hourMil = secondMil * 60;
var dayMil = hourMil * 24;
var diff = now - dt;
var days = Math.floor(diff / dayMil);
var daysRemainder = diff % dayMil;
var hours = Math.floor(daysRemainder / hourMil);
var hoursRemainder = daysRemainder % hourMil;
var seconds = Math.floor(hoursRemainder / secondMil);
var secondsRemainder = hoursRemainder % secondMil;
var milSeconds = Math.floor(secondsRemainder / milSecondMil);
console.log(days + ' days - ' + hours + ' hours - ' + seconds + ' seconds - ' + milSeconds + ' mil');
I have done this way:
var dt = new Date(value);
var now = new Date();
var date1_ms = dt.getTime();
var date2_ms = now.getTime();
var diff=(date2_ms - date1_ms) / 1000;
var tm = new Date(null, null, null, null, null, Math.floor(diff % 86400)).toTimeString().split(" ")[0];
return Math.round(diff / (60 * 60 * 24)) + 'd, ' + tm;

Lost trying to create a stopwatch

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 :)

Categories