javascript: number counter live updated - javascript

I'm looking for a way to auto-increment a number every second, starting from a given date, and it must update live when I'm on the page.
For example, I decide that today at 12.00.00 the counter will start from 0 and then it must update every second (1 at 12.00.01, 2 at 12.00.02 and so on), I want to see the number changing live on the page. If two visitors load the page at the same second they will see the same number, and the grow of the number will be syncronized. How can I do it? I'm pretty new with javascript, I found this fiddle
http://jsfiddle.net/dm6LL/5/
var amount = document.getElementById('amount');
var start = new Date("August 15, 2012 00:00:00").getTime();
var current;
update();
function update() {
var current = (new Date().getTime() - start)/1000*0.158+138276343;
amount.innerText = formatMoney(current);
}
setInterval(update,1000);
function formatMoney(amount) {
var dollars = Math.floor(amount).toString().split('');
var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof cents == 'undefined'){
cents = '00';
}else if(cents.length == 1){
cents = cents + '0';
}
var str = '';
for(i=dollars.length-1; i>=0; i--){
str += dollars.splice(0,1);
if(i%3 == 0 && i != 0) str += ',';
}
return '$' + str + '.' + cents;
}
that is similar to my goal, but it runs with money and it isn't exactly what I need.

You are quite close. All you need is a minor change to your update function. And you can skip your
formatMoney function.
Try something like this:
function update() {
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var current = (new Date().getTime() - start);
var diffDate = new Date(current);
var days = Math.round(current/oneDay);
amount.innerText = days + ":" + diffDate.getUTCHours() + ":" + diffDate.getUTCMinutes() + ":" + diffDate.getUTCSeconds();
}
Basically, it gets the difference between start and current, and puts that into amount instead of the money value.
And there's the oneDay to calculate the days between the two dates.
You can format the output however you want, but this should get your started.

Related

How to add leading zeros to the result of a date difference calculation, using moment.js?

One of the charms of the moment.js library is the perfect way it deals with sometimes having 366 days in a year ;-) and the varying length of monthes.
So I have assembled the following piece of code:
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js' type='text/javascript'></script>
<script type="text/javascript">
Date.getFormattedDateDiff = function(date1, date2) {
var b = moment(date1),
a = moment(date2),
intervals = ['years','months','weeks','days','hours','minutes','seconds'],
out = [];
for(var i=0; i<intervals.length; i++){
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
out.push('<div>' + diff + ' ' + intervals[i] + '</div><br/>');
}
return out.join(' ');
};
window.onload = function calculateInterval() {
var start = moment("2013-09-04"),
end = moment();
document.getElementById('output').innerHTML
= 'Time elapsed between "' + start.toISOString().split('T')[0]
+ '" and "' + end.toISOString().split('T')[0] + '":<br/><br/>'
+ Date.getFormattedDateDiff(start, end);
}
</script>
<p><label id="output"></label></p>
A codepen can be found here ...
Probably you will immediately notice that I am missing the leading zeros in the result.
I have tried several formatting-efforts. But unfortunately, all of them don't seem to work.
Any suggestions how to get the leading zeros in the result, so 07 years instead of 7 years, etc. are highly appreciated.
In your case you should handle it manually, because you output raw numbers. One way to do this is to use method padStart
diff.toString().padStart(2, '0')
But this won't work in older browsers, see https://caniuse.com/?search=padStart for browser support.
You could write something like this instead
function getLeadingZeroNum(num) {
return num < 10 ? '0' + num : num;
}
getLeadingZeroNum(4) // 04;
Simple if statement to prepend a 0 will work -- typeof diff() value returns number and you need to convert to a string to manipulate.
Date.getFormattedDateDiff = function(date1, date2) {
var b = moment(date1),
a = moment(date2),
intervals = ['years','months','weeks','days','hours','minutes','seconds'],
out = [];
for(var i=0; i<intervals.length; i++){
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
if (diff.toString().length == 1) {
diff = "0" + diff.toString();
}
out.push('<div>' + diff + ' ' + intervals[i] + '</div><br/>');
}
return out.join(' ');
};
window.onload = function calculateInterval() {
var start = moment("2013-09-04"),
end = moment();
document.getElementById('output').innerHTML
= 'Time elapsed between "' + start.toISOString().split('T')[0]
+ '" and "' + end.toISOString().split('T')[0] + '":<br/><br/>'
+ Date.getFormattedDateDiff(start, end);
}
You can also refer to this thread for some fantastic leading 0 methods.

Javascript counter continuously updating with specific rate run from terminal

JS counter continuously updating
Hey, first of all: I'm a newbie to coding, I'm a student and I've been struggling so much with this bit that I thought it's finally time to ask someone else. So I've been looking at this question and it works perfectly in html. However I want to run it from the terminal (I'm using node to execute the file).
I've tried to modify the code for that. But the calculation doesn't seem to work. It prints: £NaN.00
//counter
var amount = formatMoney(amount);
var startDate = new Date(2012, 07, 21);
var currentDate = new Date();
var seconds = (startDate - currentDate) / 1000;
var modifier = seconds * .158;
var current = 138276343 + modifier;
update();
function update() {
amount.innerText = formatMoney(current);
}
setInterval(function(){
current += .158;
update();
},1000);
function formatMoney(amount) {
var pounds = Math.floor(amount).toString().split('');
var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof cents == 'undefined'){
cents = '00';
}else if(cents.length == 1){
cents = cents + '0';
}
var str = '';
for(i=pounds.length-1; i>=0; i--){
str += pounds.splice(0,1);
if(i%3 == 0 && i != 0) str += ',';
}
return '£' + str + '.' + cents;
}
console.log(amount);
I'm completely out of ideas, so I would really appreciate any kind of help. Thanks!
Why are you trying to set amount.innertext in your update function and not just amount? Works when you use amount instead of amount.innertext.
//counter
var amount = formatMoney(amount);
var startDate = new Date(2012, 07, 21);
var currentDate = new Date();
var seconds = (startDate - currentDate) / 1000;
var modifier = seconds * .158;
var current = 138276343 + modifier;
update();
function update() {
amount = formatMoney(current);
}
setInterval(function(){
current += .158;
update();
},1000);
function formatMoney(amount) {
var pounds = Math.floor(amount).toString().split('');
var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof cents == 'undefined'){
cents = '00';
}else if(cents.length == 1){
cents = cents + '0';
}
var str = '';
for (i=pounds.length-1; i>=0; i--) {
str += pounds.splice(0,1);
if(i%3 == 0 && i != 0) {
str += ",";
}
}
return '£' + str + '.' + cents;
}
console.log(amount);

Java script time compare with given time

Ok I cant get my head round this, ive looked at so many posts on SF but cant figure it out.
I need to campare server time with hardcorded time.
i have try this
var breackfastCutOffTime = "5:30";
var lunchCutOffTime = "10:00";
var dinnerCutOffTime = "17:00";
var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
document.getElementById("lunch").disabled = true;
}else if(serverTime >= dinnerCutOffTime){
document.getElementById("dinner").disabled = true;
}
}
I know this cant compare because time are in text format.Some one pleace help me to compleate this.
You can write a function which converts Time(hh:mm) in minutes(mm) only. Then you can compare two times and do your operations accordingly.
pseudocode:
function convert(string time) int {
//split the time by ':'
//convert the string hh,mm to int hour,mm
//calculate total minutes
//return total minutes
}
Refer Date Api for more info.
Below is your modified code. I have commented few lines. Modify according to your logic
Fiddler link
//var breackfastCutOffTime = "5:30";
var breackfastCutOffTime = new Date();
breackfastCutOffTime.setHours(5);
breackfastCutOffTime.setMinutes(30);
//var lunchCutOffTime = "10:00";
var lunchCutOffTime = new Date();
lunchCutOffTime.setHours(10);
lunchCutOffTime.setMinutes(00);
//var dinnerCutOffTime = "17:00";
var dinnerCutOffTime = new Date();
dinnerCutOffTime.setHours(17);
dinnerCutOffTime.setMinutes(00)
var serverTime = new Date();
//var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
//if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
console.log("breackfastCutOffTime");
//document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
//document.getElementById("lunch").disabled = true;
console.log("lunchCutOffTime");
}else if(serverTime >= dinnerCutOffTime){
//document.getElementById("dinner").disabled = true;
console.log("dinnerCutOffTime");
}
//}
Explanation:
Instead of converting the Date format to string i am creating new instance of the date for each cutoff time and setting desired time to that object.
Finally compare the date objects directly.
Note: The Date objects are set according to your timezone.
You can pass the breackfastCutOffTime,lunchCutOffTime and dinnerCutOffTime to the below function and it will return true if they are equal to or greater than current time.
function compareTime(timeToCompare) {
var currentDate = new Date();
var tempDate = new Date();
var timeToCompareArray = timeToCompare.split(":");
tempDate.setHours(timeToCompareArray[0]);
tempDate.setMinutes(timeToCompareArray[1]);
if (tempDate >= currentDate) {
return true;
} else {
return false;
}
}

Change the time on a specified date with javascript

I want change the time on a specified date, i tried as following js code, but doesn't work if... in line number 11. What do i do?
var interval = self.setInterval("clock()", 1000);
function clock() {
var date = new Date();
var hourOffset = 3;
date.setUTCHours(date.getUTCHours(), date.getUTCMinutes());
var time = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 3, 21);
var dstStart = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 9, 22);
var dstEnd = date.getTime();
if (time > dstStart && time < dstEnd) hourOffset = 4; // This is line 11
date.setUTCHours(date.getUTCHours() + hourOffset, date.getUTCMinutes() + 30);
var output = date.getUTCHours() + ":" + date.getUTCMinutes() + ":" + date.getUTCSeconds();
document.getElementById("clock").innerHTML = output
}
​
I mean is this line that doesn't work:
if (time > dstStart && time < dstEnd) hourOffset = 4;
DEMO: http://jsfiddle.net/bFzny/
I'm not familiar with the date functions, but I can tell you that time is less than dstStart, which is why hourOffset is staying at 3. Also, months are 0 based indices, not 1 based. March would be 2, while September would be 8. http://jsfiddle.net/bFzny/4/ This might help you some. Remember, when using jsfiddle you don't need to enclose the code in tags.

How to get of two time values using jQuery/Javascript?

I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));

Categories