【问题标题】:How to add the date depending on month and year in javascript如何在javascript中根据月份和年份添加日期
【发布时间】:2020-01-08 08:04:05
【问题描述】:

我已经实现了一个日期选择器,在选定的日期,应该 +2 到日期。 并返回添加 +2 之前和添加 +2 之后的两个日期。

例如

从日期选择器中,会得到这样的日期Wed Jan 08 2020 15:53:01 GMT+0800 (Philippine Standard Time)

我想知道用Javascript怎么做,如果日期是Jan 31 2020 15:53:01 GMT+0800,应该是

31-01-2020,
01-02-2020

如果日期是31 Dec 2019,也应该是31-12-2019, 01-01-2020 预期输出:

08-01-2020,
09-01-2020
var result = function getAllDates("Wed Jan 08 2020 15:53:01 GMT+0800 (Philippine Standard Time)");

functions getAllDates(datestr){
   var formatDate = dateStr.toLocaleDateString("en-GB").replace(/\//g,"-");
   var splitdate = dateStr.getDate() + 2;
   var splitmonth = dateStr.getMonth();
var splityear = dateStr.getYear();
return splitdate+"-"+splitmonth+"-"+splityear
}



【问题讨论】:

  • 我在你的例子中找不到任何逻辑,我想它需要调整
  • 获得预期输出背后的逻辑是什么?
  • @MayankPatel 感谢您的回复,而不是在今天的日期添加天数,我需要在所选日期添加 2 天,
  • @MayankPatel stackoverflow.com/questions/9989382/… 我想在选定的日期 + 2 天做同样的事情
  • 表示 ex。在 jquery datepicker 中,我选择了“2020-01-08”,您需要输出 2 个日期,即“2020-01-08”和“2020-01-10”?

标签: javascript jquery arrays object


【解决方案1】:

你可以像这样简单地实现它:

$(function(){
        $(".datepicker").datepicker({
                dateFormat: 'yy-mm-dd',
                autoclose: true,
                todayHighlight: true,
            });
    });
function getResult(){
  var selectedDate = new Date($(".datepicker").val());
  var nextDate = new Date(selectedDate.getTime() + 172800000); // + 2 day in ms
  console.log(selectedDate);
  console.log(nextDate);
  $("#selected").html(selectedDate);
  $("#selected_plus_2").html(nextDate);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<input type="text" class="datepicker" />
<input type="button" onclick="getResult()" value="Get Result" />
<br />
Selected: <span id="selected"></span><br />
Selected + 2: <span id="selected_plus_2"></span>

编辑: 另一种方法是:

function getResult(){
  var selectedDate = new Date($(".datepicker").val());
  var nextDate = new Date(selectedDate);
  nextDate.setDate(selectedDate.getDate()+2);
  nextDate.toLocaleDateString();
  console.log(selectedDate);
  console.log(nextDate);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多