What Percent of Time Is It?

Here's a small repo/example I set up, updating the <meter> element with JavaScript, depending on the current date/time.

meter elements showing how much time has passed expressed as a percentage.

There isn't much to this really, just take the current timestamp, then use that to see how much of the year, month, week, and day has passed. Express these values as a percentage, and use that percentage to update the value for the meter.

Enjoy it at fun.mark.ie and read the source code on GitHub.

The code takes the following format:

 

<div class="percent__item">
  <h2>Year</h2>
  <p><span class="days-passed"></span> passed so far this year. This means that <span class="percent-year-passed"></span>% of the year has passed.</p>
  <meter class="meter meter--year" min="0" max="100" value="0"></meter>
</div>

 

const meterYear = document.querySelector('.meter--year');
const daysPassed = document.querySelector('.days-passed');
const currentDate = new Date();
const year = currentDate.getFullYear();
const isLeapYear = year % 100 === 0 ? year % 400 === 0 : year % 4 === 0;
const daysPassedValue = Math.ceil((currentDate - new Date(currentDate.getFullYear(),0,1)) / 86400000);
const daysPassedFormatted = daysPassedValue === 1 ? daysPassedValue + ' day has' : daysPassedValue + ' days have';
const percentYearPassedValue = Math.round(daysPassedValue / (isLeapYear ? 366 : 365) * 100);
daysPassed.innerText = daysPassedFormatted;
percentYearPassed.innerText = percentYearPassedValue;
meterYear.setAttribute('value', percentYearPassedValue);

 

Filed Under:

  1. Frontend Development
  2. JavaScript