Why is my javascript clock that is sped up with a multiplier not starting at the correct time?

Viewed 27

I am attempting to make a clock that is sped up for a world building game. I intend to have to clock start at the year 2104. I have tried negating a date I created in 2014 to the current date and time, multiplied the difference by 52.1429 (number of weeks in a year), and

var clock = {};
var yr2104 = new Date(2104, 0, 0, 0, 0, 0, 0);

var week = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'];
var timerID = setInterval(updateTime, 10);
updateTime();

function updateTime() {
  _now = Date.now();
  _diff = _now - (yr2104.getTime())
  cd = new Date(yr2104.getTime() + (_diff * 52.1429))
  clock.time = zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds() + "s", 3);
  clock.date = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth() + 1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()];

  console.log(clock);
};

function zeroPadding(num, digit) {
  var zero = '';
  for (var i = 0; i < digit; i++) {
    zero += '0';
  }
  return (zero + num).slice(-digit);
}

added that number to the old time. For some reason it does not start in the year 2104. What should I do? Could it be that the fact that subtracting the current time from the year 2104 gives a negative value?

Image: https://imgur.com/oYdSxy4.png

1 Answers

The algorithm I'd consider is

(Date.now() - startDate) * speedMultiplier + gameStartDate

gameStartDate is the date in 2104, startDate is the actual date the game started at (you don't currently have this), speedMultiplier would be 2 if you want it to run twice as fast as regular time for example.

I used a few UTC methods to make your clock start from midnight jan 1 2104 and not whatever the time zone is here relative to UTC. There might be a better way to do that.

var clock = {};
var yr2104 = Date.UTC(2104, 0, 1, 0, 0, 0, 0);
console.log(yr2104);
var startDate = Date.now();

var week = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'];
var timerID = setInterval(updateTime, 1000);
updateTime();

function updateTime() {

  let _diff = Date.now() - startDate;
  let cd = new Date(yr2104 + _diff * 52.1429);

  clock.time = zeroPadding(cd.getUTCHours(), 2) + ':' + zeroPadding(cd.getUTCMinutes(), 2) + ':' + zeroPadding(cd.getUTCSeconds() + "s", 3);
  clock.date = zeroPadding(cd.getUTCFullYear(), 4) + '-' + zeroPadding(cd.getUTCMonth() + 1, 2) + '-' + zeroPadding(cd.getUTCDate(), 2) + ' ' + week[cd.getDay()];

  console.log(clock);
};

function zeroPadding(num, digit) {
  var zero = '';
  for (var i = 0; i < digit; i++) {
    zero += '0';
  }
  return (zero + num).slice(-digit);
}

Related