首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jQuery:在多个日期范围内比较日期(字符串或日期对象)的最佳方法

jQuery:在多个日期范围内比较日期(字符串或日期对象)的最佳方法
EN

Stack Overflow用户
提问于 2017-10-15 09:15:26
回答 1查看 441关注 0票数 0

我有这个脚本,它比较今天的日期和多个日期范围。它可以正常工作,但是我想知道它是否足够健壮,或者它是否可以做得更好--特别是当日期字符串转换成日期对象时。能做得更聪明吗?

具有日期范围的数组必须是可读字符串,因为它们是由非技术人员维护的。

联署材料:

代码语言:javascript
运行
复制
//An array of objects containing date ranges
var datesArray = [{
  "from": "2/12/2016",
  "to": "8/12/2016",
  "schedule": "Opening hours: 9-5"
}, {
  "from": "11/10/2017",
  "to": "16/10/2017",
  "schedule": "Opening hours: 9-7"
}, {
  "from": "17/10/2017",
  "to": "22/10/2017",
  "schedule": "Closed"
}];

// Today's date
var today = new Date();

// Set a flag to be used when found
var found = false;
// For each calendar date, check if it is within a range.
for (i = 0; i < datesArray.length; i++) {
  // Get each from/to ranges
  var From = datesArray[i].from.split("/");
  var To = datesArray[i].to.split("/");
  // Format them as dates : Year, Month (zero-based), Date
  var FromDate = new Date(From[2], From[1] - 1, From[0]);
  var ToDate = new Date(To[2], To[1] - 1, To[0]);
  var schedule = datesArray[i].schedule;

  // Compare date
  if (today >= FromDate && today <= ToDate) {
    found = true;
    $("#dates").html(schedule);
    break;
  }
}

//At the end of the for loop, if the date wasn't found, return true.
if (!found) {
  console.log("Not found");
}

jSFiddle在这里

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-15 09:35:37

看看这个小提琴

我已将您的日期格式更改为mm/dd/yyyy,并删除了“/”位的拆分。守则如下:

代码语言:javascript
运行
复制
// An array of objects containing date ranges
var datesArray = [{
  "from": "12/2/2016",
  "to": "12/8/2016",
  "schedule": "Opening hours: 9-5"
}, {
  "from": "10/11/2017",
  "to": "10/16/2017",
  "schedule": "Opening hours: 9-7"
}, {
  "from": "10/17/2017",
  "to": "10/22/2017",
  "schedule": "Closed"
}];

// Today's date
var today = Date.parse(new Date());
// Set a flag to be used when found
var found = false;
// For each calendar date, check if it is within a range.
for (i = 0; i < datesArray.length; i++) {
  // Get each from/to ranges
  var From = Date.parse(datesArray[i].from);
  var To = Date.parse(datesArray[i].to);
  // Format them as dates : Year, Month (zero-based), Date
  var schedule = datesArray[i].schedule;
    console.log(From+'>>'+To);
  // Compare date
  if (today >= From && today <= To) {
    found = true;
    console.log("Opening hours: " + schedule);
    $("#dates").html(schedule);
    break;
  }
}

//At the end of the for loop, if the date wasn't found, return true.
if (!found) {
  console.log("Not found");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46753487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档