Zachmalter
Zachmalter

Reputation: 75

Javascript Time Integration

I'm currently working on a project in JavaScript that tell the user the amount of time left in a class period based on the users time. I am able to determine the time using the following code.

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}

My goal is to subtract the current time based on the user by the amount of time left in the period. Here are the period times I want to use.

Period 1 7:45 - 8:34

Period 2 8:38 - 9:30

Period 3 9:34 - 10:23

Period 4 10:27 - 11:16

Period 5 11:20 - 12:38

Period 6 12:42 - 1:31

Period 7 1:35 - 2:25

So if its 8:30 it will return to the user "There is 4 minute(s) left in period 1" In this scenario the number 4 will be represented by a variable and same applies for "1" based on the period.

Upvotes: 0

Views: 205

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48683

This is easy if you understand UTC conversion. You can find both the duration and time remaining fairly easily.

Also, make sure your time includes AM/PM or you add 12 hours to the PM times. Without doing this, your code will be a nightmare. It will also make your logic unstable and unpredictable.

var periods = [
  [ '07:45' , '08:34' ],
  [ '08:38' , '09:30' ],
  [ '09:34' , '10:23' ],
  [ '10:27' , '11:16' ],
  [ '11:20' , '12:38' ],
  [ '12:42' , '13:31' ],
  [ '13:35' , '14:25' ]
];

generatePeriods();
updateTimePeriods();
setTimeout(updateTimePeriods, 1000); // Update every second

function generatePeriods() {
  var listEl = document.getElementById('periods');
  periods.forEach(function(period) {
    listEl.appendChild(document.createElement('LI'));
  });
}
function updateTimePeriods() {
  var now = new Date();
  var children = document.getElementById('periods').childNodes;
  var i = 0;
  
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    var start = periods[i][0];
    var end = periods[i][1];
    child.innerHTML = [
      start, ' — ', end,
      ' => Duration: ', formatUTCTime(duration(start, end)),
      ', Remaining: ', formatTimeRemaining(timeLeft(now, end)),
      ', In Progress: ', isInProgress(now, start, end)
    ].join('');
  }
}
function isInProgress(now, start, end) {
  var nowTime = parseTime(formatTime(now));
  var startTime = parseTime(start);
  var endTime = parseTime(end);
  return nowTime.getTime() >= startTime.getTime()
      && nowTime.getTime() < endTime.getTime()
}
function duration(start, end) {
  var startTime = parseTime(start);
  var endTime = parseTime(end);
  return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
  var nowTime = parseTime(formatTime(now));
  var endTime = parseTime(end);
  return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
  var tokens = timeStr.split(':');
  return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
  var date = new Date(time);
  return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
  var date = new Date(time);
  return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
  var sign = '+';
  if (time < 0) { time *= -1; sign = '–'; }
  var date = new Date(time);
  return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes())  + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
<h1>Periods</h1>
<ol id="periods"></ol>

Upvotes: 1

MrBizle
MrBizle

Reputation: 418

http://momentjs.com/

This library has a really useful API and makes dealing with Dates and times in JavaScript reasonable. See "relative time"

See below example taken from this:

Countdown timer using Moment js

You obviously won't want the minutes and seconds, eventTime being a datestamp for the end of each "period"

<script>
  $(document).ready(function(){

    var eventTime = '1366549200';
    var currentTime = '1366547400';
    var leftTime = eventTime - currentTime;//Now i am passing the left time from controller itself which handles timezone stuff (UTC), just to simply question i used harcoded values.
    var duration = moment.duration(leftTime, 'seconds');
    var interval = 1000;

    setInterval(function(){
      // Time Out check
      if (duration.asSeconds() <= 0) {
        clearInterval(intervalId);
        window.location.reload(true); #skip the cache and reload the page from the server
      }

      //Otherwise
      duration = moment.duration(duration.asSeconds() - 1, 'seconds');
      $('.countdown').text(duration.days() + 'd:' + duration.hours()+ 'h:' + duration.minutes()+ 'm:' + duration.seconds() + 's');
    }, interval);
  });
  </script>

Upvotes: 2

Related Questions