How to tween a timestamp to a specific time - javascript

I have a fake clock on screen with a time of day:
<div class="time">9:14<sup>am</sup></div>
I want to make a function to be able to tween that time to another arbitrary time,
so that the clock would actually progress through the seconds and hours until it hit the new time(pseudocode):
var currentTime = {
time: 9:14am
}
function changeTime(newTime){
TweenMax.to(currentTime,.5,{
time: newTime
});
}
changeTime(12:32pm);
So in the case above, the minutes would go up by one until they hit 60, then increment the hours by one and reset to zero, then increment again to 60, etc, until they hit 12:32 (with the am switching to pm at 12:00pm).
Is there a way to do this with tweenmax and a timestamp? Or would I need to construct a custom function? Or perhaps is there a better way to tween time?

You can use something like this (and improve it, I did this quickly).
<script>
var hour, minute, second, meridian, isAm;
isAm = true;
hour = 0;
minute = 0;
second = 0;
function timerLoop () {
second++;
if(second > 59) {
second = 0;
minute++;
}
if(minute > 59) {
minute = 0;
hour++;
}
if(hour >12) {
hour = 1;
isAm = !isAm;
}
// update labels
meridian = 'a.m.';
if(!isAm) meridian = 'p.m.';
console.log(hour + ':' + minute + ':' + second + ' ' + meridian);
setTimeout(function() {
timerLoop();
}, 1000);
}
timerLoop();
</script>
I tested it for 2 mins only but the that part was working.
You'll probably want to add leading zero's to the single digits as I haven't done that. And once it is running as you want you can look at adding animations or fades to style it a bit better.

Related

simple javascript code to calculate a countdown

I'm trying to edit following code to get the output I want.
function zoo_countdown_end_day() {
if ($('.zoo-get-order-notice .end-of-day')[0]) {
var offset = $('.end-of-day').data('timezone');
var day = new Date();
var utc = day.getTime() + (day.getTimezoneOffset() * 60000);
let d = new Date(utc + (3600000*offset)),
duration = 60 * (60 - d.getMinutes());
let timer = duration, minutes;
let hours = (23 - d.getHours());//kumudu edited this
hours = hours < 10 ? '0' + hours : hours;
let label_h = $('.zoo-get-order-notice .end-of-day').data('hours');
let label_m = $('.zoo-get-order-notice .end-of-day').data('minutes');
setInterval(function () {
minutes = parseInt(timer / 60, 10);
minutes = minutes < 10 ? "1" + minutes : minutes;
$('.zoo-get-order-notice .end-of-day').text(hours + ' ' + label_h + ' ' + minutes + ' ' + label_m);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
}
zoo_countdown_end_day();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>
This is the current output:
I just want to edit countdown time to countdown from next day 4.00 P.M (hours and minuets). Because I offer next day shipping.
Ok, the long and short of this answer is that it uses 2 functions to help..
countDown: this function takes in a functionwhileCountingDown, a numberforHowLong, then another functionwhenFinishedThen
whileCountingDown being triggered EACH second with the parameter being the amount of time left in seconds
forHowLong is the amount of seconds this countdown will last
whenFinishedThen is a function that activates AFTER the countdown is over.. it can be anything(like making a new countdown as well)
timeParse: this function takes in a numberseconds and then returns a string that looks like a more human version of time
eg: timeParse(108010), 108010 is 30 hours and 10 seconds, and it would return "1 day, 6 hours, 0 minutes"
The combination of these functions are able to have a countdown system working very well.. I ALSO DO NOT KNOW WHERE YOU GET YOUR FUTURE TIME FROM,
but if you get it in a timestamp format(like 1611860671302, a value that I copied from new Date().getTime() as I was typing this),
the line where you see 30*3600, replace that line with ((dateStamp-new Date().getTime())/1000).toFixed(0)
//honestly I don't even see where it's counting down from so i just made a countdown function that works in seconds and scheduled 30 hours from now(from when you run code).. just the format would probably need changing(since i don't know what format you want)
function zoo_countdown_end_day() {
var elem=$('.zoo-get-order-notice .end-of-day')[0]
//like I said, I didn't even see where you're taking the future time from but I'll just give a future time the equivalent of +30 hours
countDown(
(t)=>elem.innerText=timeParse(t), //every second, remaining time shows in specified element
30*3600, //seconds equivalent for 30 hours.. if you have a future dateStamp, before the countdown function, let dateStamp=this datestamp you would have, THEN change this line to.. ((dateStamp-new Date().getTime())/1000).toFixed(0)
()=>console.log("Timer Complete")
)
}
zoo_countdown_end_day();
//...............................................................
//time parsing function(takes in seconds and returns a string of a formatted date[this is what can change to change the look])
function timeParse(seconds){
var words=[
(num)=>{if(num==1){return("second")}return("seconds")},//this would return a word for seconds
(num)=>{if(num==1){return("minute")}return("minutes")},//this would return a word for minutes
(num)=>{if(num==1){return("hour")}return("hours")},//this would return a word for hours
(num)=>{if(num==1){return("day")}return("days")}//this would return a word for days
]
var timeArr=[seconds]
if(timeArr[0]>=60){//if seconds >= 1 minute
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=60){//if minutes >= 1 hour
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=24){//if hours >= 1 day
timeArr.unshift(Math.floor(timeArr[0]/24))
timeArr[1]=timeArr[1]%24
}
}
}
timeArr=timeArr.reverse()
.map((a,i)=>`${a} ${words[i](a)}`)
.reverse() //puts words to values and then reverses it back to correct order
timeArr.splice(timeArr.length-1,1) //takes out seconds part from being returned leaving days, minutes and hours
return(timeArr.join(', ')) //a mixture/combination of the forEach formatting(joining numbers with words), what is returned from words array and how they're joined contributes to the formatted look
}
//...............................................................
//countDown function(that works in seconds)
function countDown(whileCountingDown, forHowLong, whenFinishedThen){
//basic run down is, whileCountingDown is a function, forHowLong is a number, whenFinishedThen is a function
//in depth run down is:
/*
whileCountingDown(with parameter of how much time left in seconds) is activated every second until forHowLong seconds has passed, then whenFinishedThen is triggered
*/
var i=setInterval(()=>{forHowLong--
if(forHowLong<=0){//count finished, determine what happens next
clearInterval(i); whenFinishedThen()
}
else{whileCountingDown(forHowLong)}//do this for each second of countdown
},1000)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>

Displaying current time in JS w/ given functions

Need to display current time in JS with the given functions.
Internet searches showed JS using Date() and Time() for gathering the info, but the date and time are not showing up in the HTML when run it.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var displayCurrentTime = function() {
var now = new Date(); //use the 'now' variable in all calculations, etc.
var Date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var hours = now.getHours()+ ":" + now.getMinutes() + ":"
+ now.getSeconds();
//Ok, problem now is getting HTML to call it up?
};
var padSingleDigit = function(num) {
if (num < 10) { return "0" + num; }
else { return num; }
};
window.onload = function() {
// set initial clock display and then set interval timer to display
// new time every second. Don't store timer object because it
// won't be needed - clock will just run.
};
Instructor's instructions:
"Note that to convert the computer’s time from a 24-hour clock to a 12-hour clock, first check to see if the hours value is greater than 12. If so, subtract 12 from the hours value and set the AM/PM value to “PM”. Also, be aware that the hours value for midnight is 0.
The starter project has four functions supplied: the $ function, the start of a displayCurrentTime() function, a padSingleDigit() function that adds a leading zero to single digits, and the start of an onload event handler.
In the displayCurrentTime() function, add code that uses the Date object to determine the current hour, minute, and second. Convert these values to a 12hour clock, determine the AM/PM value, and display these values in the appropriate span tags.
Then, in the onload event handler, code a timer that calls the displayCurrentTime() function at 1 second intervals. Also, make sure that the current time shows as soon as the page loads. (some comments have been included in the starter code to guide you on where to place things)."
In order to grap an html element you first need one. So i made a tag with an id of "clock". I then set an interval, running every 1000 milis (1 second) to give me the correctly formatted time.
clock = document.getElementById("clock");
let hours, minutes, seconds;
function checkDigits(num, hours) {
if (num < 10) {
return "0" + num
} else {
if (hours) {
return num - 12
}
return num
}
}
function updateTime() {
date = new Date();
hours = checkDigits(date.getHours(), true)
minutes = checkDigits(date.getMinutes())
seconds = checkDigits(date.getSeconds())
clock.innerHTML = hours + ":" + minutes + ":" + seconds;
}
window.onload = function() {
setInterval(function() {
updateTime()
}, 1000);
}
<h1 id="clock"></h1>

Javascript/PHP countdown timer that updates every second and counts down to a specific date and time

So the code below is the code that I was able to work with so far; however, doesn't do exactly what I need it to do.
I want to be able to call a function (aka: sundayDelta() ), however, I would love to be able to define the day of week and time of day I want the function to use in the countdown inside the calling of the function. I'm not sure if this is possible...but I was thinking something like this
sundayDelta(1,1000) which would turn into Day of Week Sunday and time of day: 1000 (10:00am). Not sure if something like this is even possible; however, I'm hoping it is. I plan on having multiple countdowns going on the same page just appearing at different times of day.
When the countdown finishes, I want it to refresh a div (doesn't matter what name the div has)
I would also love to be able to incorporate PHP server time into this that way everyone is seeing the correct countdown no matter where they are.
Any help would be great! Thanks for your input!
function plural(s, i) {
return i + ' ' + (i > 1 ? s + 's' : s);
}
function sundayDelta(offset) {
// offset is in hours, so convert to miliseconds
offset = offset ? offset * 20 * 20 * 1000 : 0;
var now = new Date(new Date().getTime() + offset);
var days = 7 - now.getDay() || 7;
var hours = 10 - now.getHours();
var minutes = now.getMinutes() - 00 ;
var seconds = now.getSeconds()- 00;
if (hours < 0){
days=days-1;
}
var positiveHours= -hours>0 ? 24-(-hours) : hours;
return [plural('day', days),
plural('hour', positiveHours),
plural('minute', minutes),
plural('second', seconds)].join(' ');
}
// Save reference to the DIV
$refresh = $('#refresh');
$refresh.text('This page will refresh in ' + sundayDelta());
// Update DIV contents every second
setInterval(function() {
$refresh.text('This page will refresh in ' + sundayDelta());
}, 1000);
When I make flexible text for intervals, I like to subtract out until nothing is left. That way you only show the non-0 values:
function sundayDelta(target_date) {
var now = new Date();
var offset = Math.floor((Date.parse(target_date) - now.valueOf()) / 1000);
var r = [];
if (offset >= 86400) {
var days = Math.floor(offset / 86400);
offset -= days * 86400;
r.push(plural('day', days));
}
if (offset >= 3600) {
var hours = Math.floor(offset / 3600);
offset -= hours * 3600;
r.push(plural('hour', hours));
}
if (offset >= 60) {
var minutes = Math.floor(offset / 60);
offset -= minutes * 60;
r.push(plural('minute', minutes));
}
if (offset != 0) {
r.push(plural('second', offset));
}
return r.join(' ');
}
In the PHP code, you can set variable this way. And we'll leave time zones out of it for now, but they could be added as well just by specifying them.
echo "target_date = '" . date('Y-m-d H:i:s', strotime('next Sunday 10am')) . "';\n";

Count-Up Timer on each page load from 0

I want to implement a count-up timer JS code that starts counting at each load page from 0. The code which I've now is like this:
var secondsTotal = 0;
setInterval(function() {
++secondsTotal;
var minutes = Math.floor(secondsTotal / 60);
var seconds = Math.floor(secondsTotal) % 60;
var milliseconds = Math.floor(secondsTotal) % 1000;
document.getElementById('counter').innerHTML = minutes + ":" + seconds + "." + milliseconds;
}, 1000);
The output format should be: 00:00.0
mm:ss.ms
So, how to output the result like above format (minutes and seconds should be exactly printed in two digits format)?
If you want to do it per-page, you're almost there. Right now, your code does not allow you to track milliseconds, as your setInterval runs every second. What I would recommend instead is something like this:
(function() {
var counter = 0,
cDisplay = document.getElementById("counter");
format = function(t) {
var minutes = Math.floor(t/600),
seconds = Math.floor( (t/10) % 60);
minutes = (minutes < 10) ? "0" + minutes.toString() : minutes.toString();
seconds = (seconds < 10) ? "0" + seconds.toString() : seconds.toString();
cDisplay.innerHTML = minutes + ":" + seconds + "." + Math.floor(t % 10);
};
setInterval(function() {
counter++;
format(counter);
},100);
})();
This does a couple of things to allow your code to run 10 times per second:
The output element, #counter, is cached and not retrieved every iteration
The formatting is kept to arithmetic operations only - modulo and division.
This now also adds leading zeroes.
If you would like to keep this counter running page-per-page, consider using document.cookies to pass the final value from page to page.
Fiddle
This serves as a good first version. However, you may want to:
Pause/re-start your timer
Reset your timer
Have multiple timers
For this reason, I will add a slightly more complex form of the above code, which will allow you to manage multiple timers. This will make use of a few OO concepts. We will use a TimerManager object to "host" our timers, and each Timer object will have a link to the manager.
The reason for this is because every timer will depend on the same setInterval() by doing it this way, rather than to have multiple setInterval() calls. This allows you to cut down on wasted clock cycles.
More on this in about 5 minutes!
Counting seconds that way isn't guaranteed to be accurate. The setInterval method can drift on you based upon the JS engine's ability to complete its other tasks. Not sure what your use case is, such as how long you expect to count up, but it's worth taking note of. See Will setInterval drift? for a detailed explanation.
I'd recommend you check out the momentjs plugin # http://momentjs.com/ and update your code to something like the following
var startTime = moment();
var el = document.getElementById('counter');
setInterval(function() {
var ms = moment().diff(startTime),
min = moment.duration(ms).minutes(),
sec = moment.duration(ms).seconds();
ms = moment.duration(ms).milliseconds();
min = (min < 10) ? "0" + min.toString() : min.toString();
sec = (sec < 10) ? "0" + sec.toString() : sec.toString();
ms = ms.toString().substring(0,2); // change this if you want to expand ms counter display
el.innerHtml = min + ":" + sec + "." + ms;
}, 50);
You're free to update the interval, and your milliseconds display without adjusting your calculations.

Javascript/Jquery Refresh timer

I have a simple system that refreshes a div every few seconds:
$(document).ready(function() {
$("#nownext").load("response.php");
var refreshId = setInterval(function() {
$("#nownext").load('response.php?randval='+ Math.random());
}, 20000);
});
Now, because of what the content is, it is more likely to update on the hour, or at half past. (Though not always). What I'd like to do it make the system refresh MORE often between a few minutes before and after the hour (and half past), just to make it more precise.
Is this possible/how would I do it without stressing out the client's computer too much?
Use setTimeout instead of setInterval so you can dynamically alter the timing of the next interval. I'm not sure what the performance implications of creating and checking the Date() object ever millisec in the "Fast" period would be, but you could always tune that frequency up closer to every second if its an issue.
start_timer = function(timing) {
var timer, d = new Date(), min = d.getMinutes(),
timeout = 20000; /* slow timeout */
if((min >= 28 && min <= 30) || min >= 58) {
timeout = 100; /* fast timeout */
}
timer = setTimeout(start_timer, timeout);
// Call your code here.
};
$(document).ready(function() {
start_timer();
});
Since the interval itself is going to be dynamic, you're going to have to use setTimeout instead.
Something like this (untested):
$(document).ready(function() {
$("#nownext").load('response.php?randval='+ Math.random());
var minutes = new Date().getMinutes(), interval = 60*10*1000; // default 10 mins
if (minutes <= 10 || (minutes > 30 && minutes < 35) || minutes > 50) {
// update once-per-minute if within the first/last 10mins of the hour, or 5mins within the half hour
interval = 60*1000;
}
setTimeout(arguments.callee, interval);
});

Categories

Resources