[英]How to add the date depending on month and year in javascript
我有一個日期選擇器,在選定的日期,應該+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
}
您可以像這樣簡單地實現它:
$(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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.