Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert output of numbers to date format with jquery

I have following setup where the output-date is created by an ACF-field (Advanced Custom Fields plugin for WordPress). The date is then put into an array by my theme (Uncode) and outputted this way. I don’t want to mess into my theme files so is there a way to format the outputted date to the desired format with jQuery?

<div class="table-container">
    <div class="output-date">20220501</div>
    <div class="output-date">20230105</div>
    <div class="output-date">20190923</div>
    ... and so on
</div>

What I want as an output:

<div class="table-container">
    <div class="output-date">May 2022</div>
    <div class="output-date">January 2023</div>
    <div class="output-date">September 2019</div>
    ... and so on
</div>

So the months should come first and must be converted to letters instead of numbers. The days can be removed.
Is there a way to do this in jQuery?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I tried:

$(".output-date").html(function (index, html) {
      return html.slice(0, html.length - 2) + '<span class="hide-date-part">' + html.slice(html.length - 2) + '</span>';
});

.hide-date-part {
    display: none;
}

This removes the days, but if there is a better way.

>Solution :

Well isn’t this a classic for chatGPT. Nevertheless, here’s my solution

function formatDate(inputDate) {
  const year = inputDate.substring(0, 4);
  const month = inputDate.substring(4, 6);
  const day = inputDate.substring(6, 8);

  // my solution
  const months = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec'.split(',');
  return months[+month - 1] + ' ' + year
}

function formatElems(selector) {
  document.querySelectorAll(selector).forEach(function(boo) {
    const inputDate = boo.innerText;
    const formattedDate = formatDate(inputDate);
    boo.innerText = formattedDate
  })
}

formatElems('.output-date');
<div class="table-container">
  <div class="output-date">20220501</div>
  <div class="output-date">20230105</div>
  <div class="output-date">20190923</div>
  ... and so on
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading