Published: Tue 13 Oct 2020

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);

 

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.