First time posting. So I have to format some text in a element that looks like this
<div class="entry-time">
2012-05-30T20:11:06+00:00
</div>
I'm trying to format this out to something more readable with moment.js. I can only do this from the front end with javascript. I wrote a function that looks like this.
$(document).ready(function() {
function formatDate(date) {
formattedDate = date.text();
var d = moment(formattedDate, "YYYY-MM-DDTHH:mm:ss");
$(date).html( d.format("dddd, MMMM Do YYYY, h:mm:ss a"));
};
formatDate($('.entry-date'));
});
This works if there is one element but when there are multiple elements it will format everything into one date. I know this has something to do with jQuery pulling in an array of elements but I have no idea how to do what I did to each element with the class of entry-date.
Can anyone help? Thank you in advance.
At the heart of what's wrong is that the jQuery .text() method gets "the combined text contents of each element in the set of matched elements, including their descendants" (api.jquery.com/text) rather than iterating over the set of elements as you intend.
Something like this should work, passing a function into the jQuery .html() setter method:
$(".entry-date").html(function(index, value) {
return moment(value, "YYYY-MM-DDTHH:mm:ss").format("dddd, MMMM Do YYYY, h:mm:ss a");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With