User288213138 posted
Hi thepast,
I have page in want to calculate hire date till now date in years, months and days textbox1 textbox2 textbox3
if month more than 12 then add on years also for days
According to your description, I made demo for your.
You can judge the number of days and months of the date separately. If the previous value is less than the latter value,
then the corresponding month and year are decremented by one.
The code:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#TextBox1").datepicker({
});
$("#TextBox2").datepicker({
onSelect: function () {
myfunc();
}
});
function diff_months(dt1, dt2) {
var d1 = dt1, d2 = dt2;
if (dt1 < dt2) {
d1 = dt2;
d2 = dt1;
}
var m = (d1.getFullYear() - d2.getFullYear()) * 12 + (d1.getMonth() - d2.getMonth());
if (d1.getDate() < d2.getDate()) {
--m;
};
return m;
}
function diff_years(year1, year2) {
var y1 = year1, y1 = year2;
if (year1 < year2) {
y1 = year2;
y2 = year1;
}
var y = (y1.getFullYear() - y2.getFullYear());
if (y1.getMonth() < y2.getMonth()) {
--y;
};
return y;
}
function myfunc() {
var start = $("#TextBox1").datepicker("getDate");
var end = $("#TextBox2").datepicker("getDate");
days = (end - start) / (1000 * 60 * 60 * 24);
$("#TextBox3").val(days + 1);
$("#TextBox4").val(diff_months(start, end));
$("#TextBox5").val(diff_years(start, end));
}
});
</script>
hire date:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
Day:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
Month:<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br />
Year:<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox><br />
The result:

Best regards,
Sam