Get current document's Last-Modified date in javascript Date object

browser, date, javascript

Solution

You can not `var anotherDateObject = new Date(Date.parse(document.lastModified));` Just because javascript does not parse a string to Date Object until it contains any separators (like `'/'` or `'-'` other than `empty space` in date part (time part has no problem with `':'`) . Javascript can parse a valid date string with spaces as separator. here it is

<html>
<body>
<script>
    var dt = document.lastModified;    
    dt = dt.replace("/", " ");
    dt = dt.replace("/", " ");
    dt = dt.replace("-", " ");
    dt = dt.replace("-", " ");
    // '/' or '-' replcae these separtors with empty space
    // Now your string can be parsed to Date Object
    var anotherDateObject = new Date(Date.parse(dt));
    alert(anotherDateObject + " -- " + anotherDateObject.getHours());        
</script>
</body>
</html>

Problem

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.

Original source