Skip to content

Instantly share code, notes, and snippets.

@xdevmaycry
Last active February 1, 2018 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xdevmaycry/b0ef73f66d9847a980edbfab4c135a77 to your computer and use it in GitHub Desktop.
Save xdevmaycry/b0ef73f66d9847a980edbfab4c135a77 to your computer and use it in GitHub Desktop.
Get Last Modified Date from a Public Accessible File (Async). No external libraries required. ECMAScript 5.
/*
*
* Fiddle: https://jsfiddle.net/w79L4wan/10/
*/
function ready(callback) {
// in case the document is already rendered
if (document.readyState!='loading') callback();
// modern browsers
else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
// IE <= 8
else document.attachEvent('onreadystatechange', function(){
if (document.readyState=='complete') callback();
});
}
ready(function (){
updateFileDate();
});
function fetchHeader(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var lastModified = xhr.getResponseHeader('Last-Modified');
formatAndUpdateDate(lastModified);
return;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
function formatAndUpdateDate(dateString) {
var parsedTime = new Date(dateString).getTime();
var a = new Date(parsedTime);
// If you prefer non-numeric month:
// var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// var month = months[a.getMonth()];
var year = a.getFullYear();
var month = a.getMonth() < 9 ? '0' + Number(a.getMonth() + 1) : Number(a.getMonth() + 1);
var date = a.getDate() < 10 ? '0' + a.getDate() : a.getDate();
var hour = a.getHours();
var min = a.getMinutes() < 10 ? '0' + a.getMinutes() : a.getMinutes();
var sec = a.getSeconds() < 10 ? '0' + a.getSeconds() : a.getSeconds();
var ampm = hour >= 12 ? 'pm' : 'am';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
var formattedDate = month + '/' + date + '/' + year + ' at ' + hour + ':' + min + ampm;
var el = document.getElementsByClassName("last-updated-date")[0];
if (el !== undefined) {
el.textContent=formattedDate;
}
}
function updateFileDate() {
var url = document.getElementById('file').href;
if (url !== undefined) {
fetchHeader(url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment