【问题标题】:How to check two month are equal or not from date format YYYY-MM-DD?如何从日期格式 YYYY-MM-DD 中检查两个月是否相等?
【发布时间】:2020-02-18 06:32:26
【问题描述】:

我有两个日期,例如 2020-12-31 和 2020-12-01,字符串格式为 yyyy-mm-dd,同时检查它应该返回 true 的月份。

假设我比较 2020-11-31 和 2020-12-31 它应该返回 false。

如果只有月份和年份有差异,它应该返回 true。

例如今天2020年2月18日,假设我选择2020年2月11日,它应该返回true,如果我选择2020年1月11日,那么它应该返回false。

不应考虑日期差异

【问题讨论】:

标签: javascript typescript


【解决方案1】:

@Maheshwaran 你可以使用这样的东西

var d1 = new Date("2020-12-31")
var d2 = new Date("2020-12-31")
return d1.getMonth() === d2.getMonth() && d1.getYear() === d2.getYear()

【讨论】:

    【解决方案2】:

    您可以使用以下代码:

    const date1 = new Date('2020-12-01');
    const date2 = new Date('2020-12-31');
    
    // if you want to return true or false based on either date or month or year difference then use the following code.
    
    const diffTime = Math.abs(date2 - date1);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
    // this way if there is difference in either date or month or year then it will return true
    if(diffDays) {
      return true;
    } else {
      return false;
    }
    

    如果您只想根据月份或年份返回 true 或 false,则可以使用以下代码。

    const date1 = new Date('2020-12-01');
    const date2 = new Date('2020-12-31');
    // return basis on difference of either month OR year 
    return date1.getMonth() === date2.getMonth() || date1.getYear() === date2.getYear()
    
    // return basis on the difference of month AND year
    return date1.getMonth() === date2.getMonth() && date1.getYear() === date2.getYear()
    

    【讨论】:

    • 假设不同年份但同月它会工作吗?比如 2019-12-31 和 2020-12-31
    • @MaheswaranS 什么对你有用?那么它应该返回 true 还是 false 呢?
    • @MaheswaranS 您没有在问题中询问年份差异。您刚刚询问了 2020-11-31 和 2020-12-31 ,即如果月份不同,则它应该返回 false。
    • @StackSlave 我已经更新了答案。错误地更新了变量名称。 :)
    • @Deep Kakkar 我也想查看年份。
    【解决方案3】:

    更短、更快、更简单的解决方案是:

    "2020-11-31".substr(5, 2) === "2020-12-31".substr(5, 2)
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多