The browser provides a way to determine a document's last-modified date by looking at document.lastModified
. This property is determined from the HTTP Last-Modified
header, and is returned as a string.
My goal is to convert this property to a Javascript Date
object. Currently I am using
var date = new Date(document.lastModified);
which successfully parses the string. However, I am curious as to whether this will work across browsers and across locales.
What is very interesting to me is that the document.lastModified
represents the same date as the HTTP Last-Modified
header given, but the strings are not identical. It seems to me that the browser parses the Last-Modified
header, converts it to its internal date representation, and then sets document.lastModified
to a string based on that. If this is the case, document.lastModified
is likely to be formatted in a way such that it can be parsed by the Javascript Date
constructor, as they are both likely using the same locale and formatting rules. But I've been unable to confirm this for sure.
Here is an example:
<!--
function makeArray() {
for (i = 0; i < makeArray.arguments.length; i++)
this[i] = makeArray.arguments[i];
}
function getFullYear(d) {
var y = d.getYear();
if (y < 1000) {
y += 1900
};
return y;
}
var days = new makeArray("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var months = new makeArray("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
function format_time(t) {
var Day = t.getDay();
var Date = t.getDate();
var Month = t.getMonth();
var Year = getFullYear(t);
timeString = "";
timeString += days[Day];
timeString += " ";
timeString += months[Month];
timeString += " ";
timeString += Date;
timeString += ", ";
timeString += Year;
return timeString;
}
// -->
m = new Date(document.lastModified);
d = new Date();
$(function() {
$('.timestamp').html(format_time(m))
});
.timestamp-wrap { font-size : 22px; font-family : 'Open Sans'; }
.timestamp { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timestamp-wrap">
Updated on <span class="timestamp"></span>
</div>
Try this ? `
function getLastMod() {
var lastMod = Date.parse(document.lastModified);
var now = new Date();
var diff = (new Date(now.toLocaleString())).getTimezoneOffset() - now.getTimezoneOffset();
if (!diff) diff = now.getTimezoneOffset() * 60000;
else diff = 0;
return lastMod - diff;
}
`
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