I am using an API that returns the time like this deal_expiration_time:1469396377 which looks like its seconds from 1970. I am trying to get a countdown in MM/SS This is in angular so I apparently can't use jQuery? I have struggled for a while and am stumped with this code. I'm trying to make it so its input: 1469396377 | output: 08:21
function(){
var x1, secs1 = 510;
x1 = setInterval(function(){myFunc1(9)}, 1000);
function myFunc1(timerId){
var minutes = Math.floor(secs1 / 60);
var seconds = secs1 % 60;
$('#timer_'+timerId).html(minutes + ':' + seconds); //assuming there is a label with Id 'timer'
secs1--;
if(secs1 == 0){
document.getElementById('timer_' + timerId).style.hidden = true;
clearInterval(x1);
}
}
}
You can get the current time using Date.now() and then manually calculate the difference in time. This function gets the difference between the given time and the current time, calculates the difference in seconds and in minutes. This difference is then formatted as a countdown string and then returned.
function getTimeDifference(expirationTime) {
var now = Date.now();
var diff = expirationTime - now;
var secDiff = Math.round(diff/1000);
var minDiff = Math.round(secDiff / 60);
var diffStr = minDiff + ":" + (secDiff - minDiff * 60);
return diffStr
}
Related
In JavaScript, how can I calculate the difference between two times that are in 24 hour format which are having different dates?
Example:
Date1 is 2019/12/31 11:00:06 AM
Date2 is 2020/01/01 01:10:07 PM.
Time difference should be 02:10:13 in hh:MM:ss format
..how can get like this when date changes in appscript
Just use the Date
const dateDiffMs = (date1,date2 ) => {
const d1 = new Date(date1);
const d2 = new Date(date2);
return d1.getTime() - d2.getTime()
}
const ms2hms = (ms) => {
const sec = Math.floor(ms / 1000)
const min = Math.floor(sec / 60)
const h = Math.floor(min / 60)
return [
h,
min % 60,
sec % 60,
];
};
const format = (n) => n < 10 ? '0' + n : n;
const hms2str = ([h, min, sec]) => {
return `${h}:${format(min)}:${format(sec)}`
}
alert(hms2str(ms2hms(dateDiffMs('2020/01/01 01:10:07 PM', '2019/12/31 11:00:06 AM')))); // 26:10:01
This code works correctly if both date1 and date2 are in the same timezone. But i would recommend you to use moment.js or some other library
I would do this by gathering the date in second since whenever computers decided to keep track of time for us sometime in the 70's (epoch). Then pass it the second value and subtract, leaving the difference.
You would then need to convert it back to a date format I presume:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8);
console.log(timeDifferenceInDate);
}, 3000);
})();
NOTE: I have used a timeout function - you will already have two dates that do not match to pop in.
EDIT: having been notified the days will not be calculated, you could maybe use date to calculate your time in seconds then use Math to create your display:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
/* var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8); */
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
timeDifferenceInDate = d + ':' + h + ':' + m + ':' + s;
console.log(timeDifferenceInDate);
}, 3000);
})();
I am counting up values on dynamically generated divs:
<div class="count">285489</div>
<div class="count">258569</div>
<div class="count">263548</div>
<div class="count">245856</div>
setInterval(function(){
$(".count").each(function() {
let el = $(this);
let time = Number(el.text()) + 1;
el.text(time);
});
}, 1000);
I want to transform those number into a HH:MM:SS format.
I have found the following snippet to achieve this:
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
I modified the setInterval() function to use this function above
setInterval(function(){
$(".prod").each(function() {
let el = $(this);
let time = Number(el.text()) + 1;
time = time.toString();
el.text(time.toHHMMSS());
});
}, 1000);
However, when I run it, the values are incremented by only one second. After the increment, the values are showing NaN:NaN:NaN.
I don't understand. Why is it showing NaN when there should always be the new value available inside the div when it next gets incremented?
setInterval() is fired inside my Ajax complete function
All I need is those values to be displayed as HH:MM:SS instead of just a plain number.
Could anybody help?
After the first call to .toHHMMSS, all the div text become HH:MM:SS formatted. On the next iteration of .setInterval, we're attempting to parse an HH:MM:SS formatted string as an int, which fails and produces a NaN (because it's Not a Number). To fix this issue, you have two options:
Write a function to translate HH:MM:SS back to seconds, and then increment and run .toHHMMSS on that.
String.prototype.fromHHMMSS = function () {
if (isNaN(this)) {
var timeStrArr = this.split(":");
var hours = Integer.parseInt(timeStrArr[0]);
var minutes = Integer.parseInt(timeStrArr[1]);
var seconds = Integer.parseInt(timeStrArr[2]);
var totalSeconds = hours * 3600 + minutes * 60 + seconds
return totalSeconds;
} else {
return Number(this);
}
}
setInterval(function(){
$(".prod").each(function() {
let el = $(this);
let time = el.text().fromHHMMSS() + 1;
time = time.toString();
el.text(time.toHHMMSS());
});
}, 1000);
Work directly on the HH:MM:SS formatted string.
The issue is that after it performs once, the element text value is no longer numeric, but in your time format.
Try something like this:
<div class="count" data-time="285489"></div>
So the variable isn't changed when you set text. Then you can use it like this:
$(".prod").each(function() {
let el = $(this);
let time = Number(el.data("time")) + 1;
el.data("time", time);
time = time.toString();
el.text(time.toHHMMSS());
});
That may not be a complete solution, but you get the idea. After setting text now, the time will still be accessible in original format.
Modify below code in for each,
let txt = el.text();
if(txt.indexOf(':')){
txt = txt.replace(/:/g,'')
}
let time = Number(txt) + 1;
When code runs for the first time it replaces the original numbers with the HHMMSS representation. You need to either convert from HHMMSS to seconds or, just simpler, store the seconds. Also, having toHHMMSS() as method of the String object actually makes it harder to use in this case.
I'm storing seconds as properties of the DOM node for simplicity but of course you can use any storage you want.
function toHHMMSS(sec_num) {
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
let $count = $(".count");
$count.each(function() {
let el = $(this);
this.time = Number(el.text());
});
setInterval(function(){
$count.each(function() {
let el = $(this);
let time = ++this.time;
el.text(toHHMMSS(time));
});
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="count">285489</div>
<div class="count">258569</div>
<div class="count">263548</div>
<div class="count">245856</div>
I have searched all over internet a lot but could not find solution.
I want a timer with descending order with minutes, seconds and milliseconds. i.e. 05:59:999 -> 5 Minutes, 59 Seconds, 999 Milliseconds.
Below is my code which give me just minutes and seconds :
var countdownTimer = '';
var upgradeTime = 300; // total sec row from the table
var seconds = upgradeTime;
function timer()
{
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
document.getElementById('timer1').innerHTML = pad(minutes) + " : " + pad(remainingSeconds);
document.getElementById("timer1").style.border = "1px solid";
document.getElementById("timer1").style.padding = "4px";
}
function pad(n)
{
return (n < 10 ? "0" + n : n);
}
$('#acstart').on('click', function(e) // Start the timer
{
clearInterval(countdownTimer);
countdownTimer = setInterval('timer()', 1000);
});
I found fiddle with seconds and milliseconds here is the link :
http://jsfiddle.net/2cufprgL/1/
On completion of the timer I need to call other action.
Thanks
Using the fiddle you included, you only need to update the displayCount function to get the result you want.
function displayCount(count) {
let res = Math.floor(count / 1000);
let milliseconds = count.toString().substr(-3);
let seconds = res % 60;
let minutes = (res - seconds) / 60;
document.getElementById("timer").innerHTML =
minutes + ' min ' + seconds + ' s ' + milliseconds + ' ms';
}
Note that your fiddle has the correct approach to countdown, everytime the timer ticks it measures the actual time left it doesn't assume that the timer was 'on time'.
I wouldn't call this clean. But I did follow through using your code. I did change it to recursive setTimeout() though.
What I did is call the interval faster than 1000ms, set a specific speed variable and then properly decrement seconds while checking for a flag when seconds becomes 0, this flag then calls stopTimer().
var countdownTimer = '';
var upgradeTime = 3; // total sec row from the table
var seconds = upgradeTime;
var milliseconds = seconds * 1000;
var speed = 50; //interval speed
function timer()
{
milliseconds = (seconds * 1000) - speed; //decrement based on speed
seconds = milliseconds / 1000; //get new value for seconds
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = (seconds % 60).toFixed(3);
if(seconds <= 0){ stopTimer(); return; } //sets a flag here for final call
document.getElementById('timer1').innerHTML = pad(minutes) + " : " + pad(remainingSeconds);
document.getElementById("timer1").style.border = "1px solid";
document.getElementById("timer1").style.padding = "4px";
setTimeout('timer()', speed);
}
function stopTimer(){
clearTimeout(countdownTimer);
console.log("IT HAS BEEN DONE");
document.getElementById('timer1').innerHTML = "00 : 00.000"
}
function pad(n)
{
return (n < 10 ? "0" + n : n);
}
clearTimeout(countdownTimer)
countdownTimer = setTimeout('timer()', speed);
<div id="timer1"></div>
Something that sorta works logically right now. It's a tad unstable because of what I was trying to do. https://codesandbox.io/s/8xr1kx8r68
Momentjs with Countdown library - its a little outdated and unmaintained but looks like it does something like what you want.
https://github.com/icambron/moment-countdown
http://countdownjs.org/readme.html
How to parse a given amount of milliseconds (e.g. 125230.41294642858) into a time format like: minutes:seconds?
var ms = 125230.41294642858,
min = 0|(ms/1000/60),
sec = 0|(ms/1000) % 60;
alert(min + ':' + sec);
Try the following
var num = Number(theTextValue);
var seconds = Math.floor(num / 1000);
var minutes = Math.floor(seconds / 60);
var seconds = seconds - (minutes * 60);
var format = minutes + ':' + seconds
Number.prototype.toTime = function(){
var self = this/1000;
var min = (self) << 0;
var sec = (self*60) % 60;
if (sec == 0) sec = '00';
return min + ':' + sec
};
var ms = (new Number('250')).toTime();
console.log(ms);
=> '0:15'
var ms = (new Number('10500')).toTime();
console.log(ms);
=> '10:30'
Even though moment.js does not provide such functionality, if you come here and you are already using moment.js, try this:
function getFormattedMs(ms) {
var duration = moment.duration(ms);
return moment.utc(duration.asMilliseconds()).format("mm:ss");
}
This workaround in moment was introduced in this Issue.
I have this chunk of javascript that's kind of hacked around from http://www.developphp.com/view.php?tid=1248 and I am seeing an error of "undefined variable - broadcast".
function cdtd(broadcast) {
/* expected date format is Month DD, YYYY HH:MM:SS */
var nextbroadcast = new Date(broadcast);
var now = new Date();
var timeDiff = nextbroadcast.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
document.getElementById("countdown").innerHTML = "<a href=\"flconlineservices.php\">Internet broadcast in progress<\/a>";
/* Run any code needed for countdown completion here */
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById("daysBox").innerHTML = days + " d";
document.getElementById("hoursBox").innerHTML = hours + " h";
document.getElementById("minsBox").innerHTML = minutes + " m";
// seconds isn't in our html code (javascript error if this isn't commented out)
/*document.getElementById("secsBox").innerHTML = seconds + " s";*/
var timer = setTimeout('cdtd(broadcast)',1000);
}
"broadcast" is passed from the page with this <script type="text/javascript">cdtd("<?php echo $nextbroadcast; ?>");</script>. $nextbroadcast is based upon the date/time when the user views the page.
I tried var broadcast;, var broadcast = "";, and var broadcast = null;. Whenever I try to declare the variable, before the function, it breaks the script.
Am I doing something incorrectly? The script is working, just fine, but I'd rather not have the error.
Change the following line:
var timer = setTimeout('cdtd(broadcast)',1000);
To this:
var timer = setTimeout(function() { cdtd(broadcast); }, 1000);
This might be where the problem is:
var timer = setTimeout('cdtd(broadcast)',1000);
You should declare var timer; above cdtd() function, and then set it like so below or outside of the function:
var func = 'cdtd(' + broadcast + ')';
timer = setTimeout(func,1000);