<div class="container">
  <input type="text" class="input" placeholder="timestamp or date value">  
  <h2 class="output">output: <span class="value"></span></h2>
</div>




<div class="footer">
  <div>
    Snippet from <a href="https://snippet.noxxxx.com/javascript/pure/#converting-date-to-time-ago" target="_blank">here</a>
  </div>
  <div>See more with my <a href="https://www.noxxxx.com" target="_blank">blog</a></div>
</div>

.container {
  text-align: center;
}
.input {
  border: 2px solid #ddd;
  padding: 10px;
  width: 200px;
}
.output {
  margin: 20px auto 0;
  width: 204px;
  text-align: left;
}


.footer {
  margin-top: 50px;
  color: #ddd;
  font-size: 12px;
  text-align: center;
}

a {
  color: #fd3737;
}
function formatDate (input) {
  const date = (input instanceof Date) ? input : new Date(input);
  const formatter = new Intl.RelativeTimeFormat('zh');
  const ranges = {
    years: 3600 * 24 * 365,
    months: 3600 * 24 * 30,
    weeks: 3600 * 24 * 7,
    days: 3600 * 24,
    hours: 3600,
    minutes: 60,
    seconds: 1
  };
  const secondsElapsed = (date.getTime() - Date.now()) / 1000;
  console.log(secondsElapsed)
  for (let key in ranges) {
    if (ranges[key] < Math.abs(secondsElapsed)) {
      const delta = secondsElapsed / ranges[key];
      return formatter.format(Math.round(delta), key);
    }
  }
}
const value = document.querySelector('.value');
const input = document.querySelector('.input');
input.value = new Date() - 10000;
value.innerText = formatDate(Date.now() - 1000000);

input.addEventListener('keydown', (e) => {
    value.innerText = formatDate(e.target.value); // given date should less than current date
})

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.