Display Page publishing date

The following code simply adds the publishing date of any page (including the year), in my case of my blog posts, extracted from the page’s meta tag. The format is customizable, - I prefer written out months. I insert it under the blog body, but you can find another place for it if you so desire.

HTML:

JAVASCRIPT:

var publishDateMeta = document.querySelector('meta[itemprop="datePublished"]');
var publishDate = publishDateMeta.getAttribute('content');
var dateElement = document.createElement('p');
var options = { year: 'numeric', month: 'long', day: 'numeric' };
var formattedDate = new Date(publishDate).toLocaleDateString('en-US', options);
dateElement.innerText = '' + formattedDate;
dateElement.classList.add('blogPublishDate');
//Find a place to insert the element:
//blogBody.insertBefore(dateElement, blogBackButtonContainer);
//or console log it:
console.log(dateElement.innerText);
CSS:

.blogPublishDate {
  text-align: center;
}

Please note that I embed this code into another piece of code and as such it lacks the DOM content loaded check. Please take care.

Previous
Previous

Typewriter effect

Next
Next

Easy CODE Mark-Up WITH “HIGHLIGHT.JS”