如何确保结束日期总是比开始日期多7天? [英] How to make sure end date is always 7 days more than start date?
问题描述
我有一个页面显示开始日期和结束日期,如下所示:
I have a page that shows the start date and end date like below:
您可以看到,默认情况下,结束日期总是比开始日期多7天。我可以更改开始日期,但是如何确保每次更改开始日期时,结束日期也要分别加上7天?
As you can see the end date is always 7 days more than the start date by default. I am allowed to change the start date but how do I make sure every time I change the start date,the end date also adds up 7 days to the respective start date?
代码:
<%
String relPath = "../../../";
String currentDate = CoreUtil.parseDate(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//get current date
Calendar cal = Calendar.getInstance();
//Number of Days to add
cal.add(Calendar.DAY_OF_MONTH, 7);
String defaultDate = sdf.format(cal.getTime());
%>
Start Date: <input class="txtStartDate" style="font: 13px/1.231 Trebuchet MS;" type="text" id="txtStartDate" name="Start Date" value="<%=currentDate%>" readonly><br><br>
End Date:   <input class="txtEndDate" style="font: 13px/1.231 Trebuchet MS;" type="text" id="txtEndDate" name="txtEndDate" value="<%=defaultDate%>" readonly required/>
编辑:
这是我的JavaScript代码:
This is my JavaScript code:
<Script>
$('#txtStartDate').datepicker();
$('#txtEndDate').datepicker();
$('#txtStartDate').change(function(){
var interval = 7;
function convertDateString(p) { return (p < 10) ? '0' + p : p; }
var startDate = new Date($(this).val());
startDate.setDate(startDate.getDate() + interval);
$('#txtEndDate').val( startDate.getFullYear() + '/' + convertDateString(startDate.getMonth() + 1) + '/' + convertDateString(startDate.getDate()));
});
</script>
基本上,每当我更改开始日期时,结束日期应自动更改为(开始日期+7天),这就是我想要做的。上面的代码应该可以使用,但是当我更改开始日期时,它并没有更改我的结束日期。
Basically whenever I change my start date, the end date should be automatically change to (start date+7 days) as well, that's all I'm trying to do. The above code should have work but it did not change my end date when I changed my start date.
推荐答案
这可能会有所帮助。
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
$('#txtStartDate').datepicker();
$('#txtEndDate').datepicker();
$('#txtStartDate').change(function(){
var interval = 7;
var startDate = new Date($(this).val());
$('#txtEndDate').val(startDate.addDays(interval));
});
这篇关于如何确保结束日期总是比开始日期多7天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!