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.
3
Answers
Well isn’t this a classic for chatGPT. Nevertheless, here’s my solution
You can use regular expression to parse the string date into a
Date
object and the INTL library to format the date the way you would like – in this case, a full month name and year:The easiest way for date time conversion in a JS file is to use moment library.
You can use the moment with jQuery like this :
You can try moment() in browser’s console of moment’s official website https://momentjs.com/