Search code examples
javascriptanimationtimestamptweengsap

How to tween a timestamp to a specific time


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?


Solution

  • 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.