javascript - 在某些浏览器中日期返回为 "Undefined"和 "NaN"?

标签 javascript json date undefined nan

今天早上我一直致力于创建一个 Web 应用程序,该应用程序从 JSON 文件获取信息 - 在本例中,是来自 @POTUS 帐户的推文信息,因为白宫刚刚公开了大量信息 - 并将其呈现屏幕上。

具体来说,我一直致力于获取 @POTUS 推文信息的 JSON 文件,并显示推文的文本和日期。日期取自时间戳,我使用了一些 JS 将其转换为对我有吸引力的格式。

我的问题是这样的:日期在 Chrome 中正确显示(我一直在测试),但是在 Safari、Firefox 或移动设备中查看它时,日期返回“undefined NaN, NaN”,其中月份是返回“未定义”,日期和年份都返回“NaN”。查看我的代码,我找不到发生这种情况的原因。

这是我的完整 HTML 文件:

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title>@POTUS</title>
      <link rel="stylesheet" href="assets/css/main.css">
      <link href="https://fonts.googleapis.com/css?family=Lato:300,900" rel="stylesheet">
   </head>
   <body>
      <div class="tweet-container">
         <header>
            <h1 class="title">
               <a class="twitter" href="http://www.twitter.com/potus" target="_blank">@POTUS</a> Tweets
            </h1>
            <p class="description">A complete archieve of tweets from President Barack Obama, presented in reverse chronological order.</p>
         </header>
         <div id="potus-tweets"></div>
         <button id="btn">New Tweet</button>
      </div>
      <script src="assets/js/tweets.js"></script>
   </body>
</html>

这是我的完整 JS 文件:

var tweetCounter = 0;
var tweetsContainer = document.getElementById("potus-tweets");
var btn = document.getElementById("btn");

btn.addEventListener("click", function(){
  var request = new XMLHttpRequest();
  request.open('GET', 'assets/js/potus.json');
  request.onload = function(){
    var potusTweets = JSON.parse(request.responseText);
    loadTweets(potusTweets);
  };
  request.send();
});

function loadTweets(data){

  var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var date = new Date(data[tweetCounter].timestamp);
  var year = date.getFullYear();
  var month = date.getMonth();
  var day = date.getDate();

  var tweet = "";

  for (i = 0; i < 1; i++){
    tweet += '<div class="tweet"><p class="copy">' + data[tweetCounter].text + '</p><p class="date">' + monthNames[month] + ' ' + day + ', ' + year + '</p></div>';
    tweetCounter++;
  };

  tweetsContainer.insertAdjacentHTML('beforeend', tweet);
};

作为引用,该项目已上线:http://thejessicafelts.github.io/projects/POTUS-Tweets/

代码可以在这里找到:https://github.com/thejessicafelts/POTUS-Tweets

任何关于为什么这不起作用的见解都将非常感激。我整个早上都在尝试解决这个问题,但我看不到任何会导致“undefined NaN,NaN”返回的东西。

提前致谢

最佳答案

首先,时间戳示例,因为它是问题中缺少的重要输入。

{ // A sample tweet in your array.
  "tweet_id": 796018814072672300,
  "in_reply_to_status_id": "",
  "in_reply_to_user_id": "",
  "timestamp": "2016-11-08 15:57:29 +0000",
  "source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
  "text": "Today, progress is on the ballot. Go vote - then make sure your friends, your family, and everyone you know votes too.",
  "retweeted_status_id": "",
  "retweeted_status_user_id": "",
  "retweeted_status_timestamp": "",
  "expanded_urls": ""
}

有了这个供引用,我将链接到 Date 的 MDN 文档。构造函数。

//Syntax:
new Date(); [1]
new Date(value); [2]
new Date(dateString); [3]
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]); [4]

来 self 从你的 json 那里捡到的元素asset,然后按照此描述,您将使用第三种语法。我将从文档中引用 dateString 参数必须符合 date.parse 方法

dateString

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

为了更接近问题的原因,我会提到 documentation对于date.parse

dateString

A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).

是的,出乎意料。在描述的下方,您可能会发现:-

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

现在听起来很熟悉。

我在 Firefox 47.0.2 上测试了相同的字符串,没有时区偏移

var a = new Date("2016-11-08 15:57:29")
a.getDate()
// returns 8
a.getMonth()
//returns 10
a.getFullYear()
//returns 2016

关于javascript - 在某些浏览器中日期返回为 "Undefined"和 "NaN"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41663709/

相关文章:

javascript - 限制正则​​表达式中的字符长度

javascript - 替换链接Javascript中的部分字符串

javascript - Highcharts 刻度位置未在多个 Y 轴上对齐

jQuery - 搜索 JSON 数组

java - 在不知道 JSON 结构的情况下在 Java 中解析嵌套的 JSON?

javascript - 图表 js。如何通过工具提示的中心对齐文本?

java - Retrofit2 - 在带有正文的 POST 上收到 400 个错误请求

java - 将日期从 14 转换为 2014

java - 根据java中的日期查找日期 - 给出错误的答案

date - Get-EventLog - 轻松过滤 'today' ?