【问题标题】:How to loop between dates that are in dmy format如何在 dmy 格式的日期之间循环
【发布时间】:2016-12-11 08:58:16
【问题描述】:

这是我的第二次约会

var startdate = '11-12-2016';
var stopdate = '13-12-2016';

我想在这两个日期之间循环。所以,我确实喜欢这个

var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
  console.log(startdate)
}

但我在浏览器中运行无限循环。

我该怎么做。

注意:

我不想为此使用 jQuery。

如果开始日期和结束日期相同,它应该只循环一次,并且输入日期将始终为 d/m/y 格式。我的代码中有什么错误。请帮忙

更新:

我弄错了日期格式,我的日期格式是 d-m-y。我怎样才能做到这一点..

【问题讨论】:

  • 您是否考虑过将循环体中的startMedicine 增加一天中的毫秒数?
  • 啊,对不起..我应该在循环内执行 startMedicine++ 吗?
  • 那只会增加一,你会得到意想不到的长循环。请重新阅读我上面的评论。
  • 我尝试添加86400,但它不起作用,你能告诉我怎么做
  • 86400 只是一个小时...

标签: javascript html loops date datetime


【解决方案1】:

使用getDate每次迭代将日期增加一天

startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');

var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);

var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
  var v  = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' +   startMedicine.getFullYear();
  console.log(v);
  startMedicine.setDate(startMedicine.getDate()+1);
}

在 js 中,月份索引从 0 开始,所以 nov 是 12 月 10 日。是 11,所以这就是我使用 getMonth() + 1 的原因 `

【讨论】:

  • 谢谢它很好用,你能告诉我日期是否是 d-m-y 格式
  • 请参阅问题中的更新。你能按照那个做吗
  • 不,它们是本机 js 形式,打印它们会将其转换为通常的 2016 年 11 月 12 日星期六 00:00:00 GMT+0900 (JST) 但如果你想我可以显示,你可以随意转换它们你
  • 是的,请告诉我如何转换它们。会有帮助的
  • 嗨,谢谢,创建了一个小提琴,但它没有输出任何结果.. jsfiddle.net/5r4L4gyo
【解决方案2】:

主要问题是您没有增加日期。

解决办法

var startdate = '11/12/2016';
var stopdate  = '11/13/2016';

var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);

var currentMedicine = startMedicine;
var dayCount = 0;

while(currentMedicine < stopMedicine){
  currentMedicine.setDate(startMedicine.getDate() + dayCount);

  // You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
  var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' +  currentMedicine.getFullYear(); // in dd/mm/yyyy format

  console.log(currentDate);

  dayCount++;
}

【讨论】:

  • 嗨,你能根据日期格式更新答案吗 d-m-y
  • 不要使用 Date 构造函数(或 Date.parse)解析日期,最好拆分字符串并将部分作为参数传递给 Date 构造函数(即手动解析它)。库可以提供帮助,但对于单一格式,它并不是真正需要的。
【解决方案3】:

您可以使用 moment js 和 moment js 持续时间。它仅用于持续时间的目的。这很容易,而且意义相同。

【讨论】:

  • 这应该是评论,而不是答案。
猜你喜欢
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 2019-11-20
相关资源
最近更新 更多