Reputation: 766
There's some problem with the dates, the expected result should be 1st the user should input the the .start_date field, the .end_date field should change according to the .days field. How the things is the date can change but not correctly. For instance, today is the 27th June, when the .days field is set to 1, the .end_date field should be 28th June. However, the result turns out to be 27th June. What's the problem with the code. Thank you.
(function($, window, document, undefined) {
$(".addSkip").click(function() {
// row instance to use `find()` for the other input classes
var $row = $(this).closest('tr');
var date = new Date($row.find(".start_date").val()),
days = parseInt($row.find(".days").val(), 10);
if (!isNaN(date.getTime())) {
date.setDate(date.getDate() + days);
$row.find(".end_date").val(date.toInputFormat());
} else {
alert("Invalid Date");
}
});
Date.prototype.toInputFormat = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1] ? mm : "0" + mm[0]) + "-" + (dd[0] ? dd : "0" + dd[0]); // padding
};
})
(jQuery, this, document);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<input type="button" size="10" value="confirm date" class="addSkip"></td>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><input type="text" size="3" name="skip[]" class="days" \> </td>
</tr>
</table>
Upvotes: 0
Views: 1084
Reputation: 158
While the answer above solves the problem and works, I'd advice against using dates that way.
What if your time zone changes ? What if someone connects from a different time zone ?
Use moment.js for that.
Upvotes: 2
Reputation: 33943
You're having this issue because you are in a timezone with minus hours from UTC.
I just added +" 0:00:00"
to the new Date()
object creation... And it fixed it.
var date = new Date($row.find(".start_date").val()+" 0:00:00")
See it in CodePen.
Upvotes: 0