在 javascript Date 对象中获取当前文档的上次修改日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13408995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:40:46  来源:igfitidea点击:

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

javascriptdatebrowser

提问by Jim Garrison

The browser provides a way to determine a document's last-modified dateby looking at document.lastModified. This property is determined from the HTTP Last-Modifiedheader, and is returned as a string.

浏览器提供了一种通过查看来确定文档的上次修改日期的方法document.lastModified。此属性由 HTTPLast-Modified标头确定,并作为字符串返回。

My goal is to convert this property to a Javascript Dateobject. Currently I am using

我的目标是将此属性转换为 JavascriptDate对象。目前我正在使用

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.lastModifiedrepresents the same date as the HTTP Last-Modifiedheader given, but the strings are not identical. It seems to me that the browser parses the Last-Modifiedheader, converts it to its internal date representation, and then sets document.lastModifiedto a string based on that. If this is the case, document.lastModifiedis likely to be formatted in a way such that it can be parsed by the Javascript Dateconstructor, as they are both likely using the same locale and formatting rules. But I've been unable to confirm this for sure.

对我来说非常有趣的是,document.lastModified表示与Last-Modified给定的 HTTP标头相同的日期,但字符串并不相同。在我看来,浏览器会解析Last-Modified标头,将其转换为其内部日期表示,然后document.lastModified根据它设置为字符串。如果是这种情况,document.lastModified很可能以一种可以被 JavascriptDate构造函数解析的方式进行格式化,因为它们都可能使用相同的语言环境和格式规则。但我一直无法肯定地证实这一点。

回答by Sami

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 spacein date part (time part has no problem with ':') . Javascript can parse a valid date string with spaces as separator. here it is

您不能var anotherDateObject = new Date(Date.parse(document.lastModified));仅仅因为 javascript 不会将字符串解析为日期对象,直到它包含任何分隔符(例如日期部分中'/''-'以外empty space(时间部分没有问题':'))。Javascript 可以解析一个有效的日期字符串,并以空格作为分隔符。这里是是

<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>

回答by livibetter

I would say you need to give a special case for Webkit-based browser until HTML5 Specification finalized.

我会说在 HTML5 规范最终确定之前,您需要为基于 Webkit 的浏览器提供一个特殊情况。

According to HTML5 draft, document.lastModifiedhas a very clear requirement for implementation:

根据HTML5 草案document.lastModified对实现有非常明确的要求:

The lastModified attribute, on getting, must return the date and time of the Document's source file's last modification, in the user's local time zone, in the following format:

  1. The month component of the date.
  2. A "/" (U+002F) character.
  3. The day component of the date.
  4. A "/" (U+002F) character.
  5. The year component of the date.
  6. A U+0020 SPACE character.
  7. The hours component of the time.
  8. A ":" (U+003A) character.
  9. The minutes component of the time.
  10. A ":" (U+003A) character.
  11. The seconds component of the time.

lastModified 属性在获取时必须返回文档源文件上次修改的日期和时间,在用户的本地时区,格式如下:

  1. 日期的月份部分。
  2. “/” (U+002F) 字符。
  3. 日期的日期部分。
  4. “/” (U+002F) 字符。
  5. 日期的年份部分。
  6. U+0020 空格字符。
  7. 时间的小时部分。
  8. “:” (U+003A) 字符。
  9. 时间的分钟部分。
  10. “:” (U+003A) 字符。
  11. 时间的秒部分。

In short words, that is "MM/DD/YYYY hh:mm:ss"in the user's local time zone. Which means Webkit would be doing it wrong when HTML5 finalized if with same requirement.

简而言之,就是"MM/DD/YYYY hh:mm:ss"在用户的本地时区。这意味着如果具有相同的要求,当 HTML5 最终确定时,Webkit 会做错。

Also, the source of modified date is required to conforms to

此外,修改日期的来源必须符合

The Document's source file's last modification date and time must be derived from relevant features of the networking protocols used, e.g. from the value of the HTTP Last-Modified header of the document, or from metadata in the file system for local files. If the last modification date and time are not known, the attribute must return the current date and time in the above format.

文档源文件的最后修改日期和时间必须从所使用的网络协议的相关特性中导出,例如从文档的 HTTP Last-Modified 标头的值,或从本地文件的文件系统中的元数据导出。如果上次修改日期和时间未知,则该属性必须以上述格式返回当前日期和时间。

For now, I think, standard per se, every browser can do whatever they like because I can't not find anything about document.lastModifiedin HTML4, XHTML, DOM 2, or DOM 3. I believe it's only defined in HTML5.

现在,我认为,标准本身,每个浏览器都可以为所欲为,因为我document.lastModified在 HTML4、XHTML、DOM 2 或 DOM 3 中找不到任何相关内容。我相信它只在 HTML5 中定义。

Once everyone conforms to standard, there would be no problem even one browser can not parse "MM/DD/YYYY hh:mm:ss", you can always reconstruct it to be ISO 8601, which is accepted in ECMAScript standard. But I think current major browsers can parse the format correctly as local time, which is also expected and standard in ECMAScript.

一旦大家都符合标准,就算是一个浏览器都解析不出来也没有问题"MM/DD/YYYY hh:mm:ss",你可以随时重构为 ISO 8601,这是 ECMAScript 标准中所接受的。但我认为目前的主流浏览器都可以将格式正确解析为本地时间,这也是 ECMAScript 中的预期和标准。

回答by Jérémy Lal

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;
}

`

`

回答by Ahsan Khurshid

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>

回答by jim

Vis-á-vis livibetter's comment, "For now, I think, standard per se, every browser can do whatever they like because I can't not find anything about document.lastModified in HTML4, XHTML, DOM 2, or DOM 3. I believe it's only defined in HTML5"

Vis-á-vis livibetter 的评论,“就目前而言,我认为,标准本身,每个浏览器都可以为所欲为,因为我在 HTML4、XHTML、DOM 2 或 DOM 3 中找不到关于 document.lastModified 的任何内容。我相信它只在 HTML5 中定义”

I believe "document.lastModified" has been around for a while. I've had it on one site for a few years now (before HTML5). Not that it really matters. If anyone cares (under Windows XP SP3) the browsers I keep around to check pages:

我相信“document.lastModified”已经存在一段时间了。我已经在一个网站上使用它几年了(在 HTML5 之前)。并不是说这真的很重要。如果有人关心(在 Windows XP SP3 下)我经常检查页面的浏览器:

· Chrome 34 still insists in returning the time in UTC (but no local time addition)
· Firefox 28 just ignores the statement "javascript:alert(document.lastModified)"!! :D
· IE8 returned local time (as others have pointed out)
· Opera 12.16 returned local time
· Safari 5.1.7 returned UTC time

· Chrome 34 仍然坚持以 UTC 返回时间(但没有添加本地时间)
· Firefox 28 只是忽略语句“javascript:alert(document.lastModified)”!!:D
· IE8 返回本地时间(正如其他人指出的那样)
· Opera 12.16 返回本地时间
· Safari 5.1.7 返回 UTC 时间

At least they're getting the date right; they all returned 11/17/09 on my home page(except Firefox which just continued to ignore)! LOL

至少他们的日期是正确的;他们都在我的主页上返回了 11/17/09(Firefox 除外,它只是继续忽略)!哈哈

It would be nice if reference sources, like W3Schools (http://www.w3schools.com/jsref/prop_doc_lastmodified.asp), would add some verbiage along these lines so folks know what to expect when the results are funky.

如果像 W3Schools ( http://www.w3schools.com/jsref/prop_doc_lastmodified.asp)这样的参考来源会沿着这些方向添加一些措辞,那么人们就会知道当结果很奇怪时会发生什么,那就太好了。

UPDATE: If you activate Tools | Web Developer | DOM Inspector, Firefox 28 happily executes "javascript:alert(document.lastModified)" and returns local time! What a mish-mash. LOL

更新:如果您激活工具 | 网络开发人员 | DOM Inspector,Firefox 28 愉快地执行“javascript:alert(document.lastModified)”并返回本地时间!真是大杂烩。哈哈

回答by Arun P Johny

As far as I can see all major browsers in use today supports this property. The value stored is in local time in the format MM/dd/yyyy HH:mm:ss.

据我所知,当今使用的所有主要浏览器都支持此属性。存储的值采用本地时间格式MM/dd/yyyy HH:mm:ss

I think you can use this property across all browsers and locales.

我认为您可以在所有浏览器和语言环境中使用此属性。