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?
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>