Showing the modified time of an HTML page using JavaScript

This JavaScript demonstrates how to show the date at which an HTML page was last modified using document.lastModified. This works because HTTP servers send the information on when a document was last modified in the form of a header

Last-Modified: Sun, 12 Dec 2010 02:30:08 GMT
and the browser parses this header and makes it into the value of document.lastModified.

Unfortunately it's not so simple to get the creation date of a file, so my method also uses extra JavaScript of the form

var created = new Date ("2010/12/12");
to include the creation date of the file. The date here needs to be in the form YYYY/MM/dd in order that all different kinds of browsers can parse it.

Here is the JavaScript used to create the created / modified string at the top of this page:

function write_last_mod ()
{
    var loc = new String (document.location);
    if (loc.match (/\.html($|\?.*)|\/$/)) {
        var last_modified = new Date (document.lastModified);
        var date_stamp = "<p><small>This page was ";
        if (typeof (created) != 'undefined') {
            date_stamp += " created on <b>"
                       + created.toDateString ()
                       + "</b> and ";
        }
        date_stamp +=    "last changed on <b>"
                       + last_modified.toDateString ()
                       + "</b>.</small></p>";
        document.writeln (date_stamp);
    }
}

This is included into each page, and it is run by a line

<script>
write_last_mod ();
</script> 
in the HTML file.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer