I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?
I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).
I tried this code:
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);
and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.
Working editor: https://jsfiddle.net/s1b2fenk/
Website's image after date changed:
Your problem is that in jQuery:
$(".date-text").html(...);
changes the HTML of all elements selected by .date-text to the same value, so they all end up showing the same date.
You can use jQuery's .each method something like:
$(".date-text").each(function (){
var months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"];
var arr = this.textContent.split('/');
this.textContent = months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-text">11/12/2018</div>
<div class="date-text">10/1/2018</div>
You might find it simpler to use POJS:
window.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.date-text').forEach(el => el.textContent = formatDateString(el.textContent))
}, false);
function formatDateString(s) {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var arr = s.split('/');
return months[arr[0] - 1] + " " + arr[1] + ", " + arr[2];
}
<div class="date-text">11/12/2018</div>
<div class="date-text">10/1/2018</div>