【问题标题】:Auction Closing Date MEAN stack拍卖结束日期平均堆栈
【发布时间】:2017-04-30 18:52:50
【问题描述】:

我正在使用 MEAN 堆栈构建一个拍卖网站,用于培训。我有一点问题来理解一件事。我为数据库中的每个产品以“2017-04-30T22:10:52.360Z”的格式存储了一个截止日期。在前端我显示了今天日期和截止日期之间的差异(类似于“30 天剩余”)与此功能:

          $scope.days =function (date) {
           var today = new Date();
           var dd = today.getDate();
           var mm = today.getMonth() + 1; //January is 0!
           var yyyy = today.getFullYear();
           if (dd < 10) {
            dd = '0' + dd
            }
           if (mm < 10) {
            mm = '0' + mm
              }
           today = yyyy + '/' + mm + '/' + dd;
           $scope.today = today;
           var date2 = new Date(today);
           var date1 = new Date(date);
           var timeDiff =(date1.getTime() - date2.getTime());
           $scope.dayDifference =((timeDiff / (1000 * 3600 * 24))-1);
            return $scope.dayDifference;
              }
           });

显然我在 html 文件中传递了另一个日期。 我的问题是:如果我做这样的事情,拍卖会在世界上不同的时间结束,例如意大利和美国的今天的日期(和时间)是不同的。还是我错了? 我知道,momentjs,但我想知道是否存在一种方法可以在前端使用 Angular 修改此函数,以修复此错误。类似的东西:如果我从美国加入该网站,它会将该日期转换为我的时区(服务器的)

【问题讨论】:

  • 日期的格式是什么?如果它是带有时区的 ISO 8601 字符串,例如“2017-04-30T22:10:52.360Z”然后您可以使用自 IE 8(以及之前的大多数浏览器)以来的所有浏览器中的内置 Date 构造函数将其转换为“本地”日期。如果是其他格式,则需要更多的工作,但不会太多。
  • var date2 = new Date(today) 可能会返回无效的日期,因为您将 today 从日期更改为字符串。
  • 嗨@RobG。如您所说,日期采用 ISO 格式。

标签: javascript angularjs date time mean-stack


【解决方案1】:

如果日期字符串采用 ISO 8601 扩展格式,例如“2017-04-30T22:10:52.360Z”,则 IE 8 之后的浏览器可以使用其内置解析器对其进行解析。此外,默认情况下,日期方法会根据主机时区偏移量进行调整,以便获取剩余天数,您可以解析 ISO 字符串并以毫秒为单位获取与用户当前日期的差异,然后转换为天数(或任何适合的单位),例如

/* Return the difference in days between supplied string date
** and host current date
** @param {string} s - Date string in ISO 8601 format, e.g. 2017-04-05T23:00:00Z
** @returns {number/string} if s is a valid date string, returns days between current host date and supplied date
**                          if s is an invalid date string, returns "Invalid date string"
*/
function daysRemaining(isoString) {
  var d = new Date(isoString);
  if (isNaN(d)) return 'Invalid date string';
  return (d - new Date()) / 8.64e7;
}

var s = '2017-05-30T22:10:52.360Z';

console.log('Days remaining: ' + daysRemaining(s).toFixed(2));

如果日期字符串不是精确的 ISO 8601 格式,一些浏览器可能会解析它,而另一些则不会。此外,如果不是上述 ISO 格式,有些人可能会将其视为 UTC,而有些人可能会将其视为本地,因此请注意。

您可能希望舍入为整天,或转换为天、小时和分钟。

请注意,IE 8 及更早版本不会解析 ISO 格式的日期字符串,其他一些旧版本的浏览器也不会。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2016-09-11
    • 1970-01-01
    相关资源
    最近更新 更多