【问题标题】:javascript - date should be from 1st Nov of current year to 10th Feb of next yearjavascript - 日期应该是从当年的 11 月 1 日到明年的 2 月 10 日
【发布时间】:2018-06-13 10:46:43
【问题描述】:

我设置了一些条件,日期应该是从今年的 11 月 1 日到明年的 2 月 10 日

这是我尝试过的

if((date.getDate() >= 1 && date.getMonth() === 11 && date.getFullYear()) && (date.getDate() <= 10 && date.getMonth() === 2 && date.getFullYear + 1)){
   condition satisfied
}

显然这是行不通的。 javascript中放置这种条件的正确方法是什么。

【问题讨论】:

  • getMonth() 基于 0,因此 nov 为 10,feb 为 1。&amp;&amp; date.getFullYear() 没有检查条件,因此始终为真。
  • 您可以考虑使用 EPOCH 作为EPOCH = new Date().getTime()var d1 = Date.UTC(2018, 10, 1); 进行比较,而不是检查多个条件
  • @AlexK.-如果年份是 0000,这不是真的。;-)

标签: javascript date date-range


【解决方案1】:

这是一个可行的解决方案:

function check(date) {
  currentYear = new Date().getFullYear()
  return  date > new Date(currentYear + '-11-01') && date < new Date(currentYear + 1 + '-02-10')
}

console.log(check(new Date())); // currently false
console.log(check(new Date('2018-12-01'))); // true
console.log(check(new Date('2019-01-31'))); // true

如下使用:

if(check(date)) {
    ...
}

【讨论】:

  • 请注意 new Date('2018-12-01') 将被视为 UTC,但 getFullYear 返回本地年份,因此除非主机时区偏移量为 + 00:00。一个好的答案应该包括对 OP 问题的解释以及您的代码如何修复它。
【解决方案2】:

代码不起作用,因为在比较日期时,您必须比较整个日期,而不仅仅是部分。您可以从 Date 实例中获取当前年份,然后使用它来创建限制日期以进行比较,例如

function testDate(date) {
  var year = new Date().getFullYear();
  return date >= new Date(year, 10, 1) &&       // 1 Nov current year
         date <= new Date(year + 1, 1, 11) - 1; // 10 Feb next year at 23:59:59.999
}

// Some tests
[new Date(2018,9,31),  // 31 Oct 2018
 new Date(2018,10,1),  //  1 Nov 2018
 new Date(2019,1,10),  // 10 Feb 2018
 new Date(2019,1,11),  // 11 Feb 2018
 new Date()]           // Current date
 .forEach(function(date) {
   console.log(date.toLocaleString(undefined, {day: '2-digit',
     month:'short', year:'numeric'}) + ': ' + testDate(date));
 });

以上所有日期都被视为主机的本地日期。

【讨论】:

    【解决方案3】:

    您可以轻松使用Moment.js

    let checkDifferenceDate = moment() >= moment("12/01/"+moment().year()) && moment() <= moment("01/31/"+moment().add(1,'year').year())
    if(checkDifferenceDate){
        //You logic here !
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多